@iobroker/socket-classes

1.5.0 • Public • Published

@iobroker/socket-classes

This library is used for following adapters:

Usage as admin

const TTL_SEC      = 3600;

const SocketAdmin  = require('@iobroker/socket-classes').SocketAdmin;
const ws           = require('@iobroker/ws-server');
const session      = require('express-session');
const utils 	   = require('@iobroker/adapter-core'); // Get common adapter utils
const AdapterStore = require(utils.controllerDir + '/lib/session.js')(session, TTL_SEC);

const store = new AdapterStore({adapter});

const io = new SocketAdmin(adapter.config, adapter, objects);
io.start(
    server,
    ws,
    {
        userKey: 'connect.sid',
        store,
        secret: adapter.config.secret
    }
);

// subscribe on all object changes
io.subscribe('objectChange', '*');


// later
io.close();

Usage as socket (ws or socketio)

const TTL_SEC      = 3600;

const ws           = require('@iobroker/ws-server');
const SocketWS     = require('@iobroker/socket-classes').SocketCommon;
const session      = require('express-session');
const utils 	   = require('@iobroker/adapter-core'); // Get common adapter utils
const AdapterStore = require(utils.controllerDir + '/lib/session.js')(session, TTL_SEC);

const store = new AdapterStore({adapter});

const settings = adapter.config;
settings.crossDomain = true;
settings.ttl = settings.ttl || TTL_SEC;

const io = new SocketWS(settings, adapter);
io.start(server.server, ws, {userKey: 'connect.sid', checkUser, store, secret: adapter.config.secret});


// later
io.close();

GUI subscribes

GUI client can send to desired instance the subscribe message

    socket.emit('clientSubscribe', 'cameras.0', 'startCamera', {width: 640, height: 480}, result => console.log('Started: ' + result));

The instance 'cameras.0' will receive message clientSubscribe with information who want to receive messages.

adapter.on('message', obj => {
    if (obj?.command === 'clientSubscribe') {
        if (obj?.message.type && obj.message.type.startsWith('startCamera/')) {
            const [, camera] = obj.message.type.split('/');
            // start camera with obj.message.data
            // ...
            
            // inform GUI that camera is started
            adapter.sendTo(obj.from, obj.command, {result: true}, obj.callback);
            this.subscribes = this.subscribes || [];
            this.subscribes.push({sid: obj.message.sid, from: obj.from, type: obj.message.type, camera});
        }
    } else
    if (obj?.command === 'clientUnsubscribe' || obj?.command === 'clientSubscribeError') {
        if (obj?.message.type && obj.message.type.startsWith('startCamera/')) {
            const [, camera] = obj.message.type.split('/');
            if (this.subscribes) {
                const pos = this.subscribes.findIndex(s => s.sid === obj.message.sid && s.from === obj.from && s.type === obj.message.type);
                if (pos !== -1) {
                    this.subscribes.splice(pos, 1);

                    // stop camera
                    // ...
                }
            }
        }
    }
});

and after that client will receive messages from instance

function sendImage(camera, data) {
    this.subscribes.forEach(it => {
        if (it.camera !== camera) {
            return;
        }
        // send image to GUI
        adapter.sendTo(it.from, 'im', {m: it.type, s: it.sid, d: data});
    });
}

Web Methods

List of commands

authenticate(user, pass, callback)

Authenticate user by login and password

  • user (string): user name
  • pass (string): password
  • callback (function): function (isUserAuthenticated, isAuthenticationUsed)

error(error)

Write error into ioBroker log

  • error (string): error text

log(text, level)

Write log entry into ioBroker log

  • text (string): log text
  • level (string): one of ['silly', 'debug', 'info', 'warn', 'error']. Default is 'debug'.

checkFeatureSupported(feature, callback)

Checks, if the same feature is supported by the current js-controller

  • feature (string): feature name like CONTROLLER_LICENSE_MANAGER
  • callback (function): function (error, isSupported)

getHistory(id, options, callback)

Get history data from specific instance

httpGet(url, callback)

Read content of HTTP(S) page server-side (without CORS and stuff)

  • url (string): Page URL
  • callback (function): function (error, {status, statusText}, body)

sendTo(adapterInstance, command, message, callback)

Send the message to specific instance

  • adapterInstance (string): instance name, e.g. history.0
  • command (string): command name
  • message (object): the message is instance dependent
  • callback (function): function (result)

sendToHost(host, command, message, callback)

Send a message to the specific host. Host can answer to the following commands: cmdExec, getRepository, getInstalled, getInstalledAdapter, getVersion, getDiagData, getLocationOnDisk, getDevList, getLogs, getHostInfo, delLogs, readDirAsZip, writeDirAsZip, readObjectsAsZip, writeObjectsAsZip, checkLogging, updateMultihost.

  • host (string): instance name, e.g. history.0
  • command (string): command name
  • message (object): the message is command-specific
  • callback (function): function (result)

authEnabled(callback)

Ask server is authentication enabled, and if the user authenticated

  • callback (function): function (isAuthenticationUsed, userName)

logout(callback)

Logout user

  • callback (function): function (error)

listPermissions(callback)

List commands and permissions

  • callback (function): function (permissions)

getUserPermissions(callback)

Get user permissions

  • callback (function): function (error, permissions)

getVersion(callback)

Get the adapter version. Not the socket-classes version!

  • callback (function): function (error, adapterVersion, adapterName)

getAdapterName(callback)

Get adapter name. Not the socket-classes version!

  • callback (function): function (error, adapterVersion)

getObject(id, callback)

Get one object

  • id (string): object ID.
  • callback (function): function (error, obj)

getObjects(list, callback)

Get all objects that are relevant for web: all states and enums with rooms

  • id (string): object ID.
  • list (string[]): optional list of IDs.
  • callback (function): function (error, obj)

subscribeObjects(pattern, callback)

Subscribe to object changes by pattern. The events will come as 'objectChange' events to the socket.

  • pattern (string): pattern like 'system.adapter.*' or array of IDs like ['system.adapter.admin.0.memRss', 'system.adapter.admin.0.memHeapTotal']
  • callback (function): function (error)

unsubscribeObjects(pattern, callback)

Unsubscribe from object changes by pattern.

  • pattern (string): pattern like 'system.adapter.*' or array of IDs like ['system.adapter.admin.0.memRss', 'system.adapter.admin.0.memHeapTotal']
  • callback (function): function (error)

getObjectView(design, search, params, callback)

Make a query to the object database.

  • design (string): 'system' or other designs like custom, but it must exist object _design/custom. Too 99,9% use system.
  • search (string): object type, like state, instance, adapter, host, ...
  • params (string): parameters for the query in form {startkey: 'system.adapter.', endkey: 'system.adapter.\u9999'}
  • callback (function): function (error)

setObject(id, obj, callback)

Set object.

  • id (string): object ID
  • obj (object): object itself
  • callback (function): function (error)

delObject(id, options, callback)

Delete object. Only deletion of flot objects is allowed

  • id (string): Object ID like, 'flot.0.myChart'
  • options (string): ignored
  • callback (function): function (error)

clientSubscribe(targetInstance, messageType, data, callback)

Client informs specific instance about subscription on its messages. After subscription the socket will receive "im" messages from desired instance

  • targetInstance (string): instance name, e.g. "cameras.0"
  • messageType (string): message type, e.g. "startRecording/cam1"
  • data (object): optional data object, e.g. {width: 640, height: 480}
  • callback (function): function (error, result), target instance MUST acknowledge the subscription and return some object as result

clientUnsubscribe(targetInstance, messageType, callback)

Client unsubscribes from specific instance's messages

  • targetInstance (string): instance name, e.g. "cameras.0"
  • messageType (string): message type, e.g. "startRecording/cam1"
  • callback (function): function (error, wasSubscribed), target instance MUST NOT acknowledge the un-subscription

getStates(pattern, callback)

Read states by pattern

  • pattern (string): optional pattern, like system.adapter.* or array of state IDs
  • callback (function): function (error, states), where states is an object like {'system.adapter.history.0': {_id: 'system.adapter.history.0', common: {name: 'history', ...}, native: {...}, 'system.adapter.history.1': {...}}}

getForeignStates(pattern, callback)

Read all states (which might not belong to this adapter) which match the given pattern

  • pattern (string): pattern like system.adapter.* or array of state IDs
  • callback (function): function (error)

getState(id, callback)

Read one state.

  • id (string): State ID like, 'system.adapter.admin.0.memRss'
  • callback (function): function (error, state), where state is an object like {val: 123, ts: 1663915537418, ack: true, from: 'system.adapter.admin.0', q: 0, lc: 1663915537418, c: 'javascript.0'}

setState(id, state, callback)

Write one state.

  • id (string): State ID like, 'system.adapter.admin.0.memRss'
  • state (any): value or object like {val: 123, ack: true}
  • callback (function): function (error, state), where state is an object like {val: 123, ts: 1663915537418, ack: true, from: 'system.adapter.admin.0', q: 0, lc: 1663915537418, c: 'javascript.0'}

getBinaryState(id, callback)

Read one binary state.

  • id (string): State ID like, 'javascript.0.binary'
  • callback (function): function (error, base64)

setBinaryState(id, base64, callback)

Write one binary state.

  • id (string): State ID like, 'javascript.0.binary'
  • base64 (string): State value as base64 string. Binary states have no acknowledged flag.
  • callback (function): function (error)

subscribe(pattern, callback)

Subscribe to state changes by pattern. The events will come as 'stateChange' events to the socket.

  • pattern (string): pattern like 'system.adapter.*' or array of states like ['system.adapter.admin.0.memRss', 'system.adapter.admin.0.memHeapTotal']
  • callback (function): function (error)

subscribeStates(pattern, callback)

Subscribe to state changes by pattern. Same as subscribe. The events will come as 'stateChange' events to the socket.

  • pattern (string): pattern like 'system.adapter.*' or array of states like ['system.adapter.admin.0.memRss', 'system.adapter.admin.0.memHeapTotal']
  • callback (function): function (error)

unsubscribe(pattern, callback)

Unsubscribe from state changes by pattern.

  • pattern (string): pattern like 'system.adapter.*' or array of states like ['system.adapter.admin.0.memRss', 'system.adapter.admin.0.memHeapTotal']
  • callback (function): function (error)

unsubscribeStates(pattern, callback)

Unsubscribe from state changes by pattern. Same as unsubscribe.

  • pattern (string): pattern like 'system.adapter.*' or array of states like ['system.adapter.admin.0.memRss', 'system.adapter.admin.0.memHeapTotal']
  • callback (function): function (error)

readFile(_adapter, fileName, callback)

Read file from ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • fileName (string): file name, e.g. main/vis-views.json
  • callback (function): function (error, data, mimeType)

readFile64(_adapter, fileName, callback)

Read file from ioBroker DB as base64 string

  • _adapter (string): instance name, e.g. vis.0
  • fileName (string): file name, e.g. main/vis-views.json
  • callback (function): function (error, base64, mimeType)

writeFile64(_adapter, fileName, data64, options, callback)

Write file into ioBroker DB as base64 string

  • _adapter (string): instance name, e.g. vis.0
  • fileName (string): file name, e.g. main/vis-views.json
  • data64 (string): file content as base64 string
  • options (object): optional {mode: 0x0644}
  • callback (function): function (error)

writeFile(_adapter, fileName, data, options, callback)

Write file into ioBroker DB as text DEPRECATED

  • _adapter (string): instance name, e.g. vis.0
  • fileName (string): file name, e.g. main/vis-views.json
  • data64 (string): file content as base64 string
  • options (object): optional {mode: 0x644}
  • callback (function): function (error)

unlink(_adapter, name, callback)

Delete file in ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • name (string): file name, e.g. main/vis-views.json
  • callback (function): function (error)

deleteFile(_adapter, name, callback)

Delete file in ioBroker DB (same as unlink, but only for files)

  • _adapter (string): instance name, e.g. vis.0
  • name (string): file name, e.g. main/vis-views.json
  • callback (function): function (error)

deleteFolder(_adapter, name, callback)

Delete file in ioBroker DB (same as unlink, but only for folders)

  • _adapter (string): instance name, e.g. vis.0
  • name (string): folder name, e.g. main
  • callback (function): function (error)

renameFile(_adapter, oldName, newName, callback)

Rename file in ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • oldName (string): current file name, e.g. main/vis-views.json
  • newName (string): new file name, e.g. main/vis-views-new.json
  • callback (function): function (error)

rename(_adapter, oldName, newName, callback)

Rename file or folder in ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • oldName (string): current file name, e.g. main/vis-views.json
  • newName (string): new file name, e.g. main/vis-views-new.json
  • callback (function): function (error)

mkdir(_adapter, dirName, callback)

Create folder in ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • dirName (string): desired folder name, e.g. main
  • callback (function): function (error)

readDir(_adapter, dirName, options, callback)

Read content of folder in ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • dirName (string): folder name, e.g. main
  • options (object): optional {filter: '*'} or {filter: '*.json'}
  • callback (function): function (error, files) where files is an array of objects, like {file: 'vis-views.json', isDir: false, stats: {size: 123}, modifiedAt: 1661336290090, acl: {owner: 'system.user.admin', ownerGroup: 'system.group.administrator', permissions: 1632, read: true, write: true}

chmodFile(_adapter, fileName, options, callback)

Change file mode in ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • fileName (string): file name, e.g. main/vis-views.json
  • options (object): {mode: 0x644} or 0x644. The first digit is user, second group, third others. Bit 1 is execute, bit 2 is write, bit 3 is read
  • callback (function): function (error)

chownFile(_adapter, fileName, options, callback)

Change file owner in ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • fileName (string): file name, e.g. main/vis-views.json
  • options (object): {owner: 'system.user.user', ownerGroup: ''system.group.administrator'} or 'system.user.user'. If ownerGroup is not defined, it will be taken from owner.
  • callback (function): function (error)

fileExists(_adapter, fileName, callback)

Check if the file or folder exists in ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • fileName (string): file name, e.g. main/vis-views.json
  • callback (function): function (error, isExist)

subscribeFiles(id, pattern, callback)

Subscribe to file changes in ioBroker DB

  • id (string): instance name, e.g. vis.0 or any object ID of type meta. id could have wildcards * too.
  • pattern (string): file name pattern, e.g. main/*.json
  • callback (function): function (error)

unsubscribeFiles(id, pattern, callback)

Unsubscribe from file changes in ioBroker DB

  • id (string): instance name, e.g. vis.0 or any object ID of type meta. id could have wildcards * too.
  • pattern (string): file name pattern, e.g. main/*.json
  • callback (function): function (error)

getAdapterInstances(adapterName, callback)

Read all instances of the given adapter, or all instances of all adapters if adapterName is not defined

  • adapterName (string): optional adapter name, e.g. history.
  • callback (function): function (error, instanceList), where instanceList is an array of instance objects, e.g. {_id: 'system.adapter.history.0', common: {name: 'history', ...}, native: {...}}

Admin Methods

List of commands

authenticate(user, pass, callback)

Authenticate user by login and password

  • user (string): user name
  • pass (string): password
  • callback (function): function (isUserAuthenticated, isAuthenticationUsed)

error(error)

Write error into ioBroker log

  • error (string): error text

log(text, level)

Write log entry into ioBroker log

  • text (string): log text
  • level (string): one of ['silly', 'debug', 'info', 'warn', 'error']. Default is 'debug'.

checkFeatureSupported(feature, callback)

Checks, if the same feature is supported by the current js-controller

  • feature (string): feature name like CONTROLLER_LICENSE_MANAGER
  • callback (function): function (error, isSupported)

getHistory(id, options, callback)

Get history data from specific instance

httpGet(url, callback)

Read content of HTTP(S) page server-side (without CORS and stuff)

  • url (string): Page URL
  • callback (function): function (error, {status, statusText}, body)

sendTo(adapterInstance, command, message, callback)

Send the message to specific instance

  • adapterInstance (string): instance name, e.g. history.0
  • command (string): command name
  • message (object): the message is instance dependent
  • callback (function): function (result)

sendToHost(host, command, message, callback)

Send a message to the specific host. Host can answer to the following commands: cmdExec, getRepository, getInstalled, getInstalledAdapter, getVersion, getDiagData, getLocationOnDisk, getDevList, getLogs, getHostInfo, delLogs, readDirAsZip, writeDirAsZip, readObjectsAsZip, writeObjectsAsZip, checkLogging, updateMultihost.

  • host (string): instance name, e.g. history.0
  • command (string): command name
  • message (object): the message is command-specific
  • callback (function): function (result)

authEnabled(callback)

Ask server is authentication enabled, and if the user authenticated

  • callback (function): function (isAuthenticationUsed, userName)

logout(callback)

Logout user

  • callback (function): function (error)

listPermissions(callback)

List commands and permissions

  • callback (function): function (permissions)

getUserPermissions(callback)

Get user permissions

  • callback (function): function (error, permissions)

getVersion(callback)

Get the adapter version. Not the socket-classes version!

  • callback (function): function (error, adapterVersion, adapterName)

getAdapterName(callback)

Get adapter name. Not the socket-classes version!

  • callback (function): function (error, adapterVersion)

getHostByIp(ip, callback)

Read the host object by IP address

  • ip (string): ip address. IPv4 or IPv6
  • callback (function): function (ip, obj). If host is not found, obj is null

requireLog(isEnabled, callback)

Activate or deactivate logging events. Events will be sent to the socket as log event. Adapter must have common.logTransporter = true

  • isEnabled (boolean): is logging enabled
  • callback (function): function (error)

readLogs(host, callback)

Get logs file from given host

  • host (string): host id, like 'system.host.raspberrypi'
  • callback (function): function (error, files), where files is array of {fileName: log/hostname/transport/file, size: 123}

delState(id, callback)

Delete state. The corresponding object will be deleted too.

  • id (string): state ID
  • callback (function): function (error)

cmdExec(host, id, cmd, callback)

Execute the shell command on host/controller. Following response commands are expected: ´cmdStdout, cmdStderr, cmdExit´

  • host (string): host name, like 'system.host.raspberrypi'
  • id (string): session ID, like Date.now()´. This session ID will come in events cmdStdout, cmdStderr, cmdExit`
  • cmd (string): command
  • callback (function): function (error)

eventsThreshold(isActive)

Used only for admin to the limited number of events to front-end.

  • isActive (boolean): if true, then events will be limited

getRatings(update, callback)

Read ratings of adapters

  • update (boolean): if true, the ratings will be read from central server, if false from local cache
  • callback (function): function (error, ratings), where ratings is object like {accuweather: {rating: {r: 3.33, c: 3}, 1.2.1: {r: 3, c: 1}},…}

getCurrentInstance(callback)

Return current instance name like admin.0

  • callback (function): function (error, namespace)

decrypt(encryptedText, callback)

Decrypts text with the system secret key

  • encryptedText (string): encrypted text
  • callback (function): function (error, decryptedText)

encrypt(plainText, callback)

Encrypts text with the system secret key

  • plainText (string): normal text
  • callback (function): function (error, encryptedText)

getIsEasyModeStrict(callback)

Returns if admin has easy mode enabled

  • callback (function): function (error, isEasyModeStrict)

getEasyMode(callback)

Get easy mode configuration

  • callback (function): function (error, easyModeConfig), where easyModeConfig is object like {strict: true, configs: [{_id: 'system.adapter.javascript.0', common: {...}}, {...}]}

getAdapters(adapterName, callback)

Read all adapters objects

  • adapterName (string): optional adapter name
  • callback (function): function (error, results), where results is array of objects like {_id: 'system.adapter.javascript', common: {...}}

updateLicenses(login, password, callback)

Read software licenses (vis, knx, ...) from ioBroker.net cloud for given user

  • login (string): cloud login
  • password (string): cloud password
  • callback (function): function (error, results), where results is array of objects like [{"json":"xxx","id":"ab","email":"dogafox@gmail.com","product":"iobroker.knx.year","version":"2","invoice":"Pxx","uuid":"uuid","time":"2021-11-16T19:53:02.000Z","validTill":"2022-11-16T22:59:59.000Z","datapoints":1000}]

getCompactInstances(callback)

Read all instances in short form to save bandwidth

  • callback (function): function (error, results), where results is an object like {'system.adapter.javascript.0': {adminTab, name, icon, enabled}}

getCompactAdapters(callback)

Read all adapters in short for to save bandwidth

  • callback (function): function (error, results), where results is an object like {'javascript': {icon, v: '1.0.1', iv: 'ignoredVersion}}

getCompactInstalled(host, callback)

Read all installed adapters in short form to save bandwidth

  • callback (function): function (error, results), where results is an object like `{'javascript': {version: '1.0.1'}}``

getCompactSystemConfig(callback)

Read system config in short form to save bandwidth

  • callback (function): function (error, systemConfig), where systemConfig is an object like {common: {...}, native: {secret: 'aaa'}}

getCompactSystemRepositories(callback)

Read repositories from cache in short form to save bandwidth

  • callback (function): function (error, repositories), where repositories is an object like {_id: 'system.repositories', common: {...}, native: {repositories: {default: {json: {_repoInfo: {...}}}}}}

getCompactRepository(host, callback)

Read current repository in short form to save bandwidth

  • callback (function): function (error, repository), where repository is an object like {'javascript': {version: '1.0.1', icon}, 'admin': {version: '1.0.1', icon}}

getCompactHosts(callback)

Read all hosts in short form to save bandwidth

  • callback (function): function (error, hosts), where hosts is an array of objects like [{_id:'system.host.raspi',common:{name:'raspi',icon:'icon',color:'blue',installedVersion:'2.1.0'},native:{hardware:{networkInterfaces:[...]}}}]

addUser(user, pass, callback)

Add new user

  • user (string): user name, like benjamin
  • pass (string): user password
  • callback (function): function (error)

delUser(user, callback)

Delete existing user. Admin cannot be deleted.

  • user (string): user name, like 'benjamin
  • callback (function): function (error)

addGroup(group, desc, acl, callback)

Add a new group.

  • group (string): user name, like 'benjamin
  • desc (string): optional description
  • acl (object): optional access control list object, like {"object":{"list":true,"read":true,"write":false,"delete":false},"state":{"list":true,"read":true,"write":true,"create":true,"delete":false},"users":{"list":true,"read":true,"write":false,"create":false,"delete":false},"other":{"execute":false,"http":true,"sendto":false},"file":{"list":true,"read":true,"write":false,"create":false,"delete":false}}
  • callback (function): function (error)

delGroup(group, callback)

Delete the existing group. Administrator group cannot be deleted.

  • group (string): group name, like 'users`
  • callback (function): function (error)

changePassword(user, pass, callback)

Change user password

  • user (string): user name, like 'benjamin`
  • pass (string): new password
  • callback (function): function (error)

getObject(id, callback)

Get one object

  • id (string): object ID.
  • callback (function): function (error, obj)

getObjects(list, callback)

Read absolutely all objects. Same as getAllObjects.

  • list (string[]): optional list of IDs.
  • callback (function): function (error, objects), where objects is an object like {'system.adapter.admin.0': {...}, 'system.adapter.web.0': {...}}

subscribeObjects(pattern, callback)

Subscribe to object changes by pattern. The events will come as 'objectChange' events to the socket.

  • pattern (string): pattern like 'system.adapter.*' or array of IDs like ['system.adapter.admin.0.memRss', 'system.adapter.admin.0.memHeapTotal']
  • callback (function): function (error)

unsubscribeObjects(pattern, callback)

Unsubscribe from object changes by pattern.

  • pattern (string): pattern like 'system.adapter.*' or array of IDs like ['system.adapter.admin.0.memRss', 'system.adapter.admin.0.memHeapTotal']
  • callback (function): function (error)

getObjectView(design, search, params, callback)

Make a query to the object database.

  • design (string): 'system' or other designs like custom, but it must exist object _design/custom. Too 99,9% use system.
  • search (string): object type, like state, instance, adapter, host, ...
  • params (string): parameters for the query in form {startkey: 'system.adapter.', endkey: 'system.adapter.\u9999'}
  • callback (function): function (error)

setObject(id, obj, callback)

Set object.

  • id (string): object ID
  • obj (object): object itself
  • callback (function): function (error)

delObject(id, options, callback)

Delete an object or objects recursively. Objects with dontDelete cannot be deleted.

  • id (string): Object ID like, 'adapterName.0.channel'
  • options (string): {recursive: true}
  • callback (function): function (error)

clientSubscribe(targetInstance, messageType, data, callback)

Client informs specific instance about subscription on its messages. After subscription the socket will receive "im" messages from desired instance

  • targetInstance (string): instance name, e.g. "cameras.0"
  • messageType (string): message type, e.g. "startRecording/cam1"
  • data (object): optional data object, e.g. {width: 640, height: 480}
  • callback (function): function (error, result), target instance MUST acknowledge the subscription and return some object as result

clientUnsubscribe(targetInstance, messageType, callback)

Client unsubscribes from specific instance's messages

  • targetInstance (string): instance name, e.g. "cameras.0"
  • messageType (string): message type, e.g. "startRecording/cam1"
  • callback (function): function (error, wasSubscribed), target instance MUST NOT acknowledge the un-subscription

getAllObjects(callback)

Read absolutely all objects

  • callback (function): function (error, objects), where objects is an object like {'system.adapter.admin.0': {...}, 'system.adapter.web.0': {...}}

extendObject(id, obj, callback)

Extend the existing object

  • id (string): object ID
  • obj (object): new parts of the object, like {common: {name: 'new name'}}
  • callback (function): function (error)

getForeignObjects(pattern, type, callback)

Read objects by pattern

  • pattern (string): pattern like system.adapter.admin.0.*
  • type (string): type of objects to delete, like state, channel, device, host, adapter. Default - state
  • callback (function): function (error, objects), where objects is an object like {'system.adapter.admin.0': {...}, 'system.adapter.web.0': {...}}

delObjects(id, options, callback)

Delete objects recursively. Objects with dontDelete cannot be deleted. Same as delObject but with recursive: true.

  • id (string): Object ID like, 'adapterName.0.channel'
  • options (string): optional
  • callback (function): function (error)

getStates(pattern, callback)

Read states by pattern

  • pattern (string): optional pattern, like system.adapter.* or array of state IDs
  • callback (function): function (error, states), where states is an object like {'system.adapter.history.0': {_id: 'system.adapter.history.0', common: {name: 'history', ...}, native: {...}, 'system.adapter.history.1': {...}}}

getForeignStates(pattern, callback)

Read all states (which might not belong to this adapter) which match the given pattern

  • pattern (string): pattern like system.adapter.* or array of state IDs
  • callback (function): function (error)

getState(id, callback)

Read one state.

  • id (string): State ID like, 'system.adapter.admin.0.memRss'
  • callback (function): function (error, state), where state is an object like {val: 123, ts: 1663915537418, ack: true, from: 'system.adapter.admin.0', q: 0, lc: 1663915537418, c: 'javascript.0'}

setState(id, state, callback)

Write one state.

  • id (string): State ID like, 'system.adapter.admin.0.memRss'
  • state (any): value or object like {val: 123, ack: true}
  • callback (function): function (error, state), where state is an object like {val: 123, ts: 1663915537418, ack: true, from: 'system.adapter.admin.0', q: 0, lc: 1663915537418, c: 'javascript.0'}

getBinaryState(id, callback)

Read one binary state.

  • id (string): State ID like, 'javascript.0.binary'
  • callback (function): function (error, base64)

setBinaryState(id, base64, callback)

Write one binary state.

  • id (string): State ID like, 'javascript.0.binary'
  • base64 (string): State value as base64 string. Binary states have no acknowledged flag.
  • callback (function): function (error)

subscribe(pattern, callback)

Subscribe to state changes by pattern. The events will come as 'stateChange' events to the socket.

  • pattern (string): pattern like 'system.adapter.*' or array of states like ['system.adapter.admin.0.memRss', 'system.adapter.admin.0.memHeapTotal']
  • callback (function): function (error)

subscribeStates(pattern, callback)

Subscribe to state changes by pattern. Same as subscribe. The events will come as 'stateChange' events to the socket.

  • pattern (string): pattern like 'system.adapter.*' or array of states like ['system.adapter.admin.0.memRss', 'system.adapter.admin.0.memHeapTotal']
  • callback (function): function (error)

unsubscribe(pattern, callback)

Unsubscribe from state changes by pattern.

  • pattern (string): pattern like 'system.adapter.*' or array of states like ['system.adapter.admin.0.memRss', 'system.adapter.admin.0.memHeapTotal']
  • callback (function): function (error)

unsubscribeStates(pattern, callback)

Unsubscribe from state changes by pattern. Same as unsubscribe.

  • pattern (string): pattern like 'system.adapter.*' or array of states like ['system.adapter.admin.0.memRss', 'system.adapter.admin.0.memHeapTotal']
  • callback (function): function (error)

readFile(_adapter, fileName, callback)

Read file from ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • fileName (string): file name, e.g. main/vis-views.json
  • callback (function): function (error, data, mimeType)

readFile64(_adapter, fileName, callback)

Read file from ioBroker DB as base64 string

  • _adapter (string): instance name, e.g. vis.0
  • fileName (string): file name, e.g. main/vis-views.json
  • callback (function): function (error, base64, mimeType)

writeFile64(_adapter, fileName, data64, options, callback)

Write file into ioBroker DB as base64 string

  • _adapter (string): instance name, e.g. vis.0
  • fileName (string): file name, e.g. main/vis-views.json
  • data64 (string): file content as base64 string
  • options (object): optional {mode: 0x0644}
  • callback (function): function (error)

writeFile(_adapter, fileName, data64, options, callback)

Write file into ioBroker DB as base64 string

  • _adapter (string): instance name, e.g. vis.0
  • fileName (string): file name, e.g main/vis-views.json
  • data64 (string): file content as base64 string
  • options (object): optional {mode: 0x0644}
  • callback (function): function (error)

unlink(_adapter, name, callback)

Delete file in ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • name (string): file name, e.g. main/vis-views.json
  • callback (function): function (error)

deleteFile(_adapter, name, callback)

Delete file in ioBroker DB (same as unlink, but only for files)

  • _adapter (string): instance name, e.g. vis.0
  • name (string): file name, e.g. main/vis-views.json
  • callback (function): function (error)

deleteFolder(_adapter, name, callback)

Delete file in ioBroker DB (same as unlink, but only for folders)

  • _adapter (string): instance name, e.g. vis.0
  • name (string): folder name, e.g. main
  • callback (function): function (error)

renameFile(_adapter, oldName, newName, callback)

Rename file in ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • oldName (string): current file name, e.g. main/vis-views.json
  • newName (string): new file name, e.g. main/vis-views-new.json
  • callback (function): function (error)

rename(_adapter, oldName, newName, callback)

Rename file or folder in ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • oldName (string): current file name, e.g. main/vis-views.json
  • newName (string): new file name, e.g. main/vis-views-new.json
  • callback (function): function (error)

mkdir(_adapter, dirName, callback)

Create folder in ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • dirName (string): desired folder name, e.g. main
  • callback (function): function (error)

readDir(_adapter, dirName, options, callback)

Read content of folder in ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • dirName (string): folder name, e.g. main
  • options (object): optional {filter: '*'} or {filter: '*.json'}
  • callback (function): function (error, files) where files is an array of objects, like {file: 'vis-views.json', isDir: false, stats: {size: 123}, modifiedAt: 1661336290090, acl: {owner: 'system.user.admin', ownerGroup: 'system.group.administrator', permissions: 1632, read: true, write: true}

chmodFile(_adapter, fileName, options, callback)

Change file mode in ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • fileName (string): file name, e.g. main/vis-views.json
  • options (object): {mode: 0x644} or 0x644. The first digit is user, second group, third others. Bit 1 is execute, bit 2 is write, bit 3 is read
  • callback (function): function (error)

chownFile(_adapter, fileName, options, callback)

Change file owner in ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • fileName (string): file name, e.g. main/vis-views.json
  • options (object): {owner: 'system.user.user', ownerGroup: ''system.group.administrator'} or 'system.user.user'. If ownerGroup is not defined, it will be taken from owner.
  • callback (function): function (error)

fileExists(_adapter, fileName, callback)

Check if the file or folder exists in ioBroker DB

  • _adapter (string): instance name, e.g. vis.0
  • fileName (string): file name, e.g. main/vis-views.json
  • callback (function): function (error, isExist)

subscribeFiles(id, pattern, callback)

Subscribe to file changes in ioBroker DB

  • id (string): instance name, e.g. vis.0 or any object ID of type meta. id could have wildcards * too.
  • pattern (string): file name pattern, e.g. main/*.json
  • callback (function): function (error)

unsubscribeFiles(id, pattern, callback)

Unsubscribe from file changes in ioBroker DB

  • id (string): instance name, e.g. vis.0 or any object ID of type meta. id could have wildcards * too.
  • pattern (string): file name pattern, e.g. main/*.json
  • callback (function): function (error)

getAdapterInstances(adapterName, callback)

Read all instances of the given adapter, or all instances of all adapters if adapterName is not defined

  • adapterName (string): optional adapter name, e.g. history.
  • callback (function): function (error, instanceList), where instanceList is an array of instance objects, e.g. {_id: 'system.adapter.history.0', common: {name: 'history', ...}, native: {...}}

Changelog

1.5.0 (2024-02-22)

  • (bluefox) Extended getObjects function with the possibility to read the list of IDs in admin

1.4.6 (2023-10-19)

  • (bluefox) Added publishInstanceMessageAll command

1.4.4 (2023-10-11)

  • (bluefox) Caught errors by subscribe/unsubscribe

1.4.3 (2023-10-07)

  • (foxriver76) do not await the subscribes anymore

1.4.2 (2023-09-28)

  • (bluefox) Corrected error by unsubscribing on client disconnect

1.4.1 (2023-09-12)

  • (foxriver76) do not cancel follow subscribes if one subscribe has an error

1.4.0 (2023-09-11)

  • (foxriver76) fixed crash on invalid patterns with js-controller version 5

1.3.3 (2023-08-01)

  • (bluefox) Implemented subscribing of a client on messages from specific instance
  • (bluefox) Moved checkFeatureSupported to regular connection and not only admin

1.2.0 (2023-07-07)

  • (foxriver76) fixed crash on invalid patterns with js-controller version 5
  • (bluefox) extended the getObjects function with the possibility to read the list of IDs

1.1.5 (2023-03-13)

  • (bluefox) Added command name

1.1.3 (2023-03-12)

  • (bluefox) Treat json5 as json

1.1.2 (2023-03-03)

  • (bluefox) Allow deletion of fullcalendar objects

1.1.1 (2022-12-22)

  • (bluefox) Corrected error with subscribe

1.1.0 (2022-12-22)

  • (bluefox) Added user check to many commands
  • (bluefox) Downgrade axios to 0.27.2

1.0.2 (2022-11-08)

  • (bluefox) Function getObjectsfor web was extended by devices, channels and enums

1.0.1 (2022-10-10)

  • (bluefox) Fixed error with delObject

0.5.5 (2022-10-09)

  • (Apollon77) Prepare for future js-controller versions

0.5.4 (2022-09-23)

  • (bluefox) Fixed error in delObjects method

0.5.3 (2022-08-24)

  • (bluefox) Caught error by subscribe

0.5.2 (2022-08-19)

  • (bluefox) Added command getCompactSystemRepositories

0.5.0 (2022-07-20)

  • (bluefox) Buffer conversion errors caught and handled

0.4.12 (2022-07-08)

  • (bluefox) Corrected getAdapterInstances method

0.4.11 (2022-07-05)

  • (bluefox) Corrected log transportation

0.4.10 (2022-06-22)

  • (bluefox) Corrected getAdapterInstances

0.4.9 (2022-06-20)

  • (bluefox) Do not show error with failed authentication

0.4.7 (2022-06-20)

  • (bluefox) Allowed overloading system language

0.4.6 (2022-06-20)

  • (bluefox) updated passport

0.4.5 (2022-06-20)

  • (bluefox) allowed running socket.io behind reverse proxy

0.4.4 (2022-06-09)

  • (bluefox) Do not show requireLog message

0.4.3 (2022-06-03)

  • (bluefox) Allowed call of getAdapterInstances for non admin

0.4.2 (2022-05-23)

  • (bluefox) Corrected renameFile command for admin

0.4.1 (2022-05-23)

  • (bluefox) Corrected changePassword command for admin

0.4.0 (2022-05-19)

  • (bluefox) Added support of socket.io 4.x

0.3.2 (2022-05-19)

  • (bluefox) Hide warn messages

0.3.1 (2022-05-16)

  • (bluefox) Added back compatibility with js-controller@4.0 for writeDirAsZip

0.3.0 (2022-05-16)

  • (bluefox) Process writeDirAsZip locally

0.2.1 (2022-05-12)

  • (bluefox) fixed getObjects command

0.2.0 (2022-05-09)

  • (bluefox) fixed delObjects command

0.1.10 (2022-05-09)

  • (bluefox) Added support for fileChanges

0.1.9 (2022-05-07)

  • (bluefox) Corrected readLogs command and implement file subscriptions

0.1.7 (2022-05-05)

  • (bluefox) Caught some sentry errors

0.1.6 (2022-05-05)

  • (bluefox) fixed delObject command

0.1.5 (2022-04-25)

  • (bluefox) added updateRatings

0.1.4 (2022-04-24)

  • (bluefox) added passportSocket

0.1.2 (2022-04-24)

  • (bluefox) initial commit

License

The MIT License (MIT)

Copyright (c) 2020-2024 Bluefox dogafox@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Package Sidebar

Install

npm i @iobroker/socket-classes

Weekly Downloads

8,104

Version

1.5.0

License

MIT

Unpacked Size

240 kB

Total Files

9

Last publish

Collaborators

  • foxriver76
  • iobluefox
  • bluefox
  • apollon77
  • ldittmar
  • alcalzone