The Programmable driver runs your own driver code on the device. You paste a driver written in JavaScript, in the same form as the drivers of the device, and optionally its schema (the form of the gateway and of its addresses); the gateway runs it in an isolated container and takes care of everything around it: licence, container, logs, restarts. Its addresses behave like those of any other driver: routes, logging, alarms, dashboards.
Use it for a protocol, a device or a web API that no driver of the device covers:
Driver key:
custom— listed as Programmable driver under System in Gateway driver. Licence: only with a Full licence, the bundle of all products; this driver has no licence of its own. Platforms: Linux devices with docker; the driver is not offered on a device without docker, nor on Windows.
The example driver, named ping, is a short reference of what a driver can do; its code is commented line by line in the Driver code and Schema code tabs.
%ping:ping and %ping:setpoint, both created by the driver.%ping:ping changes every 5 seconds (0 / 1). Set Mode to counter in the gateway form: the field Maximum appears and the value counts up to it.21.5 to %ping:setpoint: it becomes its value. %ping:ping refuses a write.console.log, console.info, console.warn and console.error (see Logs and diagnostics).Editor also offers Reload the code stored on the box (discard the changes), Download as a file and Upload... (load a
.jsfile into the editor; it is saved only with Save). An unsaved change is shown in orange.
Name and Description are common to all drivers: see Gateways. A programmable gateway has no Cluster ID: it always runs in its own process. The form then shows the parameters of your schema (section Parameters, or the name of your schema), followed by the section Driver.
| Label | JSON key | Default | Description |
|---|---|---|---|
| Driver from | json.codeFrom |
this gateway | Use the code and the schema of another programmable gateway of the device instead of a copy (see section 4.8). |
| Box network without isolation | json.allowHostNetwork |
false |
Shown only when the schema asks for the host network. Ticked: the container uses the network of the device (needed for broadcast and multicast). Not ticked: it keeps an isolated network (bridge). |
| (your parameters) | json.<key> |
— | Every field of your schema is stored directly in json, for example json.url, and the code reads it in gateway.json.url. |
| (JSON only) | json.code |
— | The driver code (Driver code tab). |
| (JSON only) | json.schemaCode |
— | The schema code (Schema code tab). Empty: generic form. |
| (JSON only) | json.container |
— | Container settings, computed at each save from the declaration of the schema (see section 4.5): {"network", "publish", "sftp", "ftp", "guest"}. Do not edit it in the interface. |
| (JSON only) | json.publishPorts |
— | Additional published ports, comma-separated: 502, 1502:502 (device port:container port), 192.168.1.10:1502:502, with an optional /udp. |
| (JSON only) | json.serialPorts |
— | Additional serial devices given to the container: /dev/... paths or USB devices of the device. |
| (JSON only) | json.sftpPort |
2323 |
Port of the SFTP share of /data/files, when the schema declares it. |
| (JSON only) | json.ftpPort |
2121 |
Port of the FTP share of /data/files, when the schema declares it. |
The keys of this table are reserved: do not use them as parameters of your own driver. Keys starting with __ are reserved too.
The json object of the gateway created in section 1 (code shortened):
{
"code": "exports.regexs = [/^%ping:/] ...",
"schemaCode": "exports.schema = { name : 'Ping example', ... }",
"mode": "toggle",
"period": 5000,
"max": 10,
"container": {"network": "none", "sftp": false, "ftp": false, "publish": "", "guest": false}
}
The gateway imposes no format: the address names are those of your driver. Give them a prefix of your own, declared in the code (exports.regexs = [/^%ping:/]) and in the schema (regex : /^%ping:/), which no other driver of the device uses; the interface recognises the driver of an address by its prefix. The driver reference table lists the prefixes in use.
Examples, from the examples of this page:
%ping:setpoint — a writable value of the example driver%rest:power.active — the value power.active of a JSON document (section 5.2)%line:temperature — a value exchanged with a TCP client (section 5.3)Without address form in your schema, addresses use this generic form:
| Label | JSON key | Default | Description |
|---|---|---|---|
| Name | name |
— | The address name, with the prefix of your driver. |
| Description | description |
— | Free text. |
| Datatype | json.datatype |
json |
How a value given as text is converted for this address, for example a value typed in the interface: number, string, boolean (true, 1, false, 0) or json (JSON, or the text itself when it is not valid JSON). |
| Log | log |
none |
History policy. |
Log and Store value work the same way for every driver: see Log and Store value policies. Your code can also create the addresses itself (insertAddress, see section 4.3), as the examples do.
| Property | Value |
|---|---|
| Readable | Yes, when the code has a read method and accepts the address |
| Writable | Yes, when the code has a write method and accepts the address |
| Created automatically | When the code creates them |
| Routable | Yes |
| Loggable | Yes |
exports.process(console, gateway, peers, onUpdate) returns the methods of the driver.connect, read, write, extra methods) and relays to the device what your code emits (connect, newValue, newStatus...). Your code never talks to the device software directly: the libraries it receives only show this gateway and its addresses.The code is exactly a driver file of the device:
exports.regexs = [/^%my:/] // the prefix of your addresses
// exports.manageStatus = true // only if the code sends the status of its addresses itself
exports.process = function(console, gateway, peers, onUpdate){
var methods = {}
methods.connect = function(callback){
// open the connection, then:
peers().emit('connect')
peers().emit('ready')
callback()
}
methods.read = function(name, callback){ callback(null, 42) }
methods.write = function(name, value, callback){ callback() }
methods.acceptsRead = function(name, callback){ callback(null, /^%my:/.test(name)) }
methods.acceptsWrite = function(name, value, callback){ callback(null, true) }
methods.shutdown = function(callback){ callback() }
return methods
}
Arguments of exports.process:
| Argument | Description |
|---|---|
console |
The log of the gateway: console.log, info, warn, error. |
gateway |
This gateway: gateway.id, gateway.name and gateway.json, its parameters (without code and schemaCode). |
peers |
peers() emits the events of the driver; peers('supervision').require('gateways', callback) gives the address library, limited to this gateway (section 4.3). |
onUpdate |
onUpdate(function(gateway){...}) is called when the gateway is saved without restarting the driver (updateGateway with doNotRestartDriver); gateway is the new configuration. A save from the interface restarts the driver. |
Methods returned:
| Method | Called when |
|---|---|
connect(callback) |
The driver starts. Open the connection, then emit connect and ready. |
read(name, callback) |
A value is read (polling, Read in the interface): callback(null, value), or callback(error). |
write(name, value, callback) |
A value is written (route, logic circuit, dashboard, API): callback(), or callback(error) to refuse it. |
acceptsRead(name, callback) / acceptsWrite(name, value, callback) |
The device asks whether an address can be read / written: callback(null, true). Without them, every address is readable if read exists and writable if write exists. Note the three arguments of acceptsWrite. |
import(name, valueText, date, callback) |
Optional: a value imported for one of its addresses. |
shutdown(callback) |
The driver stops: close timers, sockets and serial ports, then callback() within 10 s. |
startMonitor(options, callback) / stopMonitor(callback) |
Optional: a frame monitor. callback('start'), then callback(null, {timestamp, direction, raw, summary}) for each frame (direction = rx or tx), and callback('keepalive') at least every 20 s. |
| any other name | An extra method, called with callGatewayMethod(gateway, name, [arguments], callback) of the Peers API or from the menu of the schema. When your code brings a new extra method, the gateway restarts once by itself to publish it (log: new driver methods (hello) : restarting the gateway once to publish them). |
Events emitted with peers().emit(...):
| Event | Meaning |
|---|---|
connect |
The driver is connected: the gateway turns green. Emit it within 30 s of connect(), or emit extendConnect every 15 s at most while you wait for a device. Without it, the device restarts the driver. |
ready |
The driver is ready, after connect. |
newValue, name, value, text, date |
A new value: peers().emit('newValue', '%my:temp', 21.5, '21.5', new Date()). |
newStatus, name, status |
The status of one address, online or offline. Only with exports.manageStatus = true; otherwise every address goes online when the gateway connects. |
disconnect |
The connection is lost: the device restarts the driver. |
The module exports exports.acceptsRead = function(name, gateway){...} and exports.acceptsWrite = function(name, value, gateway){...} (synchronous, returning true or false) are also accepted, as in the drivers of the device. Do not add a licence check or container handling to your code: the gateway does both.
peers('supervision').require('gateways', callback) gives these functions, limited to this gateway and its addresses (an address key is its id or its name):
| Function | Description |
|---|---|
getGateway(id, cb), getGateways(cb) |
This gateway only, without its code. |
getAddressesByGateway(id, cb) |
Its addresses. |
getAddress(key, cb), getLastValue(key, cb), readValue(key, cb), writeValue(key, value, cb) |
One of its addresses. getLastValue gives the last value kept by the device, for example to restore a setpoint after a restart. |
insertAddress({name, description, json}, cb), updateAddress({id, ...}, cb), deleteAddress(key, cb) |
Manage its addresses. |
updateGateway({description, json, doNotRestartDriver}, cb) |
Change its own parameters. The code, the schema and the container settings cannot be changed this way: these keys are ignored. |
Events: on('addressInsertedGw ' + gateway.id, fn), 'addressUpdatedGw ', 'addressDeletedGw ', 'gatewayUpdated ', 'newValue', 'newStatus' |
Changes of its addresses, made in the interface or by the API. |
peers('supervision').require('system', callback) gives only gps(cb), the products of the licence. Any other module is refused at once: module 'loggers' is not available to a programmable driver (available : gateways, system). Another gateway is refused too: gateway 1 is not part of this gateway.
Node.js modules. require() finds the modules built into Node.js (net, http, https, dgram, crypto...), the modules of the device software (for example mqtt), the compiled modules with requireCompiled('serialport'), and the libraries you upload to /data/files/node_modules (section 4.7). There is no shell and no npm in the container.
The schema is exactly a schema file of the device (exports.schema = {...}). It runs in the browser of the person who opens the gateway and builds:
getDefaultGatewayOptions(gateway), getGatewayForm(gateway, form), getGatewayField(key, value), and testGatewayOptions(gateway, callback) to refuse a save (callback(['error text'], gateway));addressSchemas, getDefaultAddressOptions, getAddressForm, getAddressField;getGatewayMenu(gateway, close) returns [{label, icon, onclick}] (the example calls its extra method hello with callGatewayMethod);getGridOptions(tabName, gateway) returns an HTML element (a div) that the schema fills; onInterfaceReady(tabName, tab) is called the first time the tab opens (tab.on('show', ...) to resize, tab.on('removed', ...) to clean up);locales : {'KEY' : {'en' : ..., 'fr' : ..., 'de' : ...}}, used by helper : 'KEY' in a field.Field types (nodeType): Text, Number (min, max), Select (values), Checkbox, Password, Port, Duration, TextArea, Ip, Domain, and SerialInterfacesAutocompeter: the serial ports of the device and of its USB adapters.
The gateway adds by itself the section Driver and the tabs Driver code, Schema code and Files. With an empty schema, the gateway form has only the name and the description, and addresses use the generic form of section 3.2.
require()is not available in a schema. After saving the schema, reopen the gateway to see the new form.
The schema declares what the driver needs, in exports.schema.container. Nothing is set by hand: at each save, the gateway computes json.container from this declaration and from the parameters.
| Declaration | Effect |
|---|---|
(none) or {network : 'none'} |
No network (serial driver, computation). |
{network : 'bridge'} |
An isolated network of its own: outgoing connections (TCP client, HTTP, MQTT...) through the device; nothing comes in. |
{network : 'bridge', publish : ['json.port/tcp']} |
A server: the port given by the field json.port is published on every interface of the device. Also accepted: a fixed port (502, '47808/udp') or {field : 'json.port', proto : 'udp'}. |
{network : 'host'} |
The network of the device without isolation, for broadcast and multicast (BACnet/IP, KNX IP, discovery). Effective only when Box network without isolation is ticked on the gateway; otherwise bridge is used. |
{shares : {sftp : true, ftp : true}} |
Shares /data/files over SFTP (port json.sftpPort, 2323) and FTP (port json.ftpPort, 2121), for the administrator accounts of the device. |
The declaration can be a function of the parameters, for a driver with a client and a server mode:
container : function(json){
return json.mode == 'server' ? {network : 'bridge', publish : ['json.port/tcp']} : {network : 'bridge'}
}
A serial port needs no declaration: see the next section.
Every parameter of the gateway whose value designates a serial port, a /dev/tty… or /dev/serial/… path, or a USB device chosen with a SerialInterfacesAutocompeter field, is given to the container automatically, and your code receives the /dev path in that same parameter. Example: with a field json.port set to /dev/ttyS0, the container gets /dev/ttyS0 and gateway.json.port is /dev/ttyS0.
// schema: 'json.port' : {nodeType : 'SerialInterfacesAutocompeter', label : 'Serial port'}
var SerialPort = requireCompiled('serialport')
var port = new SerialPort(gateway.json.port, {baudRate : 9600, dataBits : 8, parity : 'none', stopBits : 1})
port.on('data', function(buffer){ /* decode the frame */ })
A port that is not plugged in when the gateway starts is not given to the container (log: serial device /dev/ttyUSB0 not present, not exposed to the container (plug it and restart the driver)). Never use a port that another gateway already opens. See Serial ports and USB adapters.
Each programmable gateway has its own folder, /data/files for the code. The Files tab shows it as a tree, with the same right-click menu as the FILE tab of the HTTP driver: Download (Download (zip) for a folder), Upload here..., New folder here..., Rename..., Remove; the top line gives Refresh, Upload a file... and New folder... for the root. The tab works even when the gateway is stopped or its code fails; uploads are limited to 100 MB per file (30 MB while the gateway is stopped).
driver.js and driver.schema.js at the root are the code and the schema of the gateway, read-only in this tab./data/files/node_modules/<name>, with its dependencies, is found by require('<name>') before the modules of the device. Restart the gateway after the upload./data/files (the rest of the container is read-only; /tmp is a 64 MB temporary folder).For several identical devices, keep the code in one gateway and set Driver from on the others: they use its code and schema, and keep their own parameters, addresses, serial ports and files. Their code tabs are read-only, and changing the code of the source gateway restarts them too. Only one level is possible: a gateway cannot use the driver of a gateway that itself uses Driver from.
Use Export gateway and Import of the gateway menu, as for every driver (see Gateways). For a programmable gateway:
/data/files to include (30 MB at most);The container gives the code the least it needs:
The container of a deleted programmable gateway, and its network, are removed the next time a programmable gateway starts.
A programmable gateway is created like any gateway with the Peers API. Give json.container yourself: the interface is not there to compute it.
peers('supervision').require('gateways', function(err, gws){
gws.insertGateway({
name : 'REST poller',
driver : 'custom',
active : 1,
json : {
code : codeText, // the driver code (text)
schemaCode : schemaText, // the schema code (text), or ''
url : 'http://192.168.1.50/status.json',
period : 60,
container : {network : 'bridge', publish : '', sftp : false, ftp : false, guest : false}
}
}, function(err, id){
// then: gws.callGatewayMethod(id, 'hello', ['box'], function(err, answer){ ... })
})
})
The Files tab uses these extra methods of the gateway, also available through callGatewayMethod: filesList → [{path, dir, size, mtime, readOnly}], filesMkdir [folder, name], filesRename [path, newName], filesRm [path] (paths relative to /data/files, '' = the root).
Every example below is a complete driver: paste the code in Driver code and the schema in Schema code, save, and reopen the gateway.
The driver inserted with every new gateway (section 1.3) shows in a few lines: addresses created by the code, a periodic value, a writable value restored after a restart with getLastValue, an extra method hello called from the gateway menu, a field shown only in one mode, a check at save, helpers in three languages, and container : {network : 'none'}. To see it again, create a new programmable gateway, or download driver.js and driver.schema.js from its Files tab.
Reads a JSON document every Period seconds and publishes each value as an address, named after its path in the document. With the document
{"device": "meter-1", "online": true, "power": {"active": 1203, "reactive": 85.5}, "energy": 45211}
the driver creates and updates:
| Address | Datatype | Value |
|---|---|---|
%rest:device |
string |
meter-1 |
%rest:online |
boolean |
true |
%rest:power.active |
number |
1203 |
%rest:power.reactive |
number |
85.5 |
%rest:energy |
number |
45211 |
It sends the status of its addresses itself (exports.manageStatus): offline when the request fails or when the document no longer contains the value. The schema declares container : {network : 'bridge'}: outgoing connections only. Untick Create addresses to keep only the addresses you create by hand.
Driver code:
// REST poller: reads a JSON document over HTTP(S) every « period » seconds and publishes each value as an address
// %rest:<path>, e.g. {"current" : {"temperature_2m" : 3.4}} -> %rest:current.temperature_2m = 3.4
exports.regexs = [/^%rest:/]
exports.manageStatus = true // this driver sends the status of its addresses itself
exports.process = function(console, gateway, peers, onUpdate){
var methods = {}, values = {}, known = {}, timer = null, gws = null, stopped = false
var cfg = readParameters(gateway.json)
function readParameters(json){
return {
url : String(json.url || ''),
period : Math.max(5, parseInt(json.period) || 60) * 1000,
autoCreate : json.autoCreate !== false && json.autoCreate !== 'false'
}
}
function flatten(obj, prefix, out){
Object.keys(obj).forEach(function(k){
var v = obj[k], p = prefix ? prefix + '.' + k : k
if(v !== null && typeof v == 'object' && !Array.isArray(v)) flatten(v, p, out)
else if(typeof v == 'number' || typeof v == 'boolean' || typeof v == 'string') out[p] = v
})
return out
}
function getJson(url, callback){
var lib = url.indexOf('https:') == 0 ? require('https') : require('http')
var req = lib.get(url, {timeout : 10000}, function(res){
var body = ''
res.setEncoding('utf8')
res.on('data', function(d){ body += d })
res.on('end', function(){
if(res.statusCode != 200) return callback('HTTP ' + res.statusCode)
try{ callback(null, JSON.parse(body)) }catch(e){ callback('invalid JSON (' + e.message + ')') }
})
})
req.on('timeout', function(){ req.destroy(new Error('timeout')) })
req.on('error', function(e){ callback(e.message) })
}
function publish(name, value){
values[name] = value
peers().emit('newValue', name, value, value + '', new Date())
peers().emit('newStatus', name, 'online')
}
function poll(){
getJson(cfg.url, function(err, doc){
if(stopped) return
if(err){
console.warn('poll failed : ' + err)
Object.keys(known).forEach(function(name){ peers().emit('newStatus', name, 'offline') })
}else{
var flat = flatten(doc, '', {})
Object.keys(flat).forEach(function(path){
var name = '%rest:' + path
if(known[name]) return publish(name, flat[path])
if(!cfg.autoCreate) return
known[name] = true
gws.insertAddress({name : name, description : path, json : {datatype : typeof flat[path]}}, function(err){
if(err) return console.error('cannot create ' + name, err)
publish(name, flat[path])
})
})
// an address of the table that the document no longer contains
Object.keys(known).forEach(function(name){ if(!flat.hasOwnProperty(name.slice(6))) peers().emit('newStatus', name, 'offline') })
}
timer = setTimeout(poll, cfg.period)
})
}
methods.connect = function(callback){
if(!/^https?:\/\//.test(cfg.url)){
console.error('no valid URL in the gateway parameters') // no 'connect' : the gateway restarts the driver
return callback && callback()
}
peers('supervision').require('gateways', function(err, lib){
if(err) return console.error('gateways library unavailable', err)
gws = lib
gws.getAddressesByGateway(gateway.id, function(err, addresses){
;(addresses || []).forEach(function(a){ known[a.name] = true })
// addresses added or removed by hand in the table
gws.on('addressInsertedGw ' + gateway.id, function(a){ known[a.name] = true })
gws.on('addressDeletedGw ' + gateway.id, function(a){ delete known[a.name] })
peers().emit('connect')
peers().emit('ready')
console.info('polling ' + cfg.url + ' every ' + (cfg.period / 1000) + ' s')
poll()
})
})
if(callback) callback()
}
methods.read = function(name, callback){ callback(null, values.hasOwnProperty(name) ? values[name] : null) }
methods.acceptsRead = function(name, callback){ callback(null, /^%rest:/.test(name)) }
// no write method: the addresses are read-only
methods.shutdown = function(callback){
stopped = true
clearTimeout(timer)
callback()
}
onUpdate(function(gw){
cfg = readParameters(gw.json)
clearTimeout(timer)
poll()
})
return methods
}
Schema code:
exports.schema = {
name : 'REST poller',
regex : /^%rest:/,
container : {network : 'bridge'}, // outgoing connections only
locales : {
'REST_URL' : {'en' : "Address of the JSON document, http:// or https://", 'fr' : "Adresse du document JSON, http:// ou https://", 'de' : "Adresse des JSON-Dokuments, http:// oder https://"},
'REST_PERIOD' : {'en' : "Polling period, in seconds (5 at least).", 'fr' : "Période de lecture, en secondes (5 au moins).", 'de' : "Abfrageperiode in Sekunden (mindestens 5)."},
'REST_AUTO' : {'en' : "Create an address for every value of the document.", 'fr' : "Créer une adresse pour chaque valeur du document.", 'de' : "Für jeden Wert des Dokuments eine Adresse anlegen."}
},
getDefaultGatewayOptions : function(gateway){
return {name : '', description : '', json : {url : '', period : 60, autoCreate : true}}.deepExtend(gateway || {})
},
getGatewayForm : function(gateway, form){
var schema = this, o = this.getDefaultGatewayOptions(gateway)
return ['name', 'description', 'json.url', 'json.period', 'json.autoCreate'].map(function(key){
return schema.getGatewayField(key, key.indexOf('json.') == 0 ? o.json[key.slice(5)] : o[key])
})
},
getGatewayField : function(key, value){
var f = {
'name' : {nodeType : 'Text', label : 'Name'},
'description' : {nodeType : 'Text', label : 'Description'},
'json.url' : {nodeType : 'Text', label : 'URL', helper : 'REST_URL'},
'json.period' : {nodeType : 'Number', label : 'Period (s)', min : 5, helper : 'REST_PERIOD'},
'json.autoCreate' : {nodeType : 'Checkbox', label : 'Create addresses', helper : 'REST_AUTO'}
}[key]
if(!f) return
var out = {name : key}
for(var k in f) out[k] = f[k]
if(value !== undefined) out.value = value
return out
},
testGatewayOptions : function(gateway, callback){
var errors = [], url = String((gateway.json || {}).url || '')
if(!/^https?:\/\/[^\s]+$/.test(url)) errors.push('the URL must start with http:// or https://')
callback(errors, gateway)
}
}
The json object of the gateway:
{
"url": "http://192.168.1.50/api/status",
"period": 60,
"autoCreate": true,
"container": {"network": "bridge", "sftp": false, "ftp": false, "publish": "", "guest": false}
}
The gateway listens on a TCP port and a third-party system (SCADA, script, PLC) reads and writes values with text commands, one per line:
| Command | Answer |
|---|---|
SET temperature 21.5 |
OK — %line:temperature takes the value 21.5 (the address is created if needed, number or string) |
GET temperature |
temperature=21.5 — or the last value written by the device to %line:temperature |
LIST |
the names, one per line, then END |
| anything else | ERR unknown command, ERR unknown <name> |
A session:
SET temperature 21.5
OK
SET mode eco
OK
GET temperature
temperature=21.5
LIST
temperature
mode
END
The addresses %line:... are writable: a route from any driver to %line:setpoint makes the value available to the client, and a route from %line:temperature sends what the client writes to another protocol. After a restart, the last values are restored with getLastValue.
The schema declares container : {network : 'bridge', publish : ['json.port/tcp']}: the port of the field TCP port is published on the device. Changing the port in the form publishes the new one.
Driver code:
// Line server: a third-party system connects over TCP and reads or writes values with text commands
// GET <name> -> <name>=<value>
// SET <name> <value> -> OK (the value of %line:<name> changes in the box; the address is created if needed)
// LIST -> the names, one per line, then END
// A value written by the box (route, logic circuit, dashboard) to %line:<name> is what GET returns.
exports.regexs = [/^%line:/]
exports.process = function(console, gateway, peers, onUpdate){
var net = require('net')
var methods = {}, values = {}, known = {}, server = null, clients = [], gws = null
var port = parseInt(gateway.json.port) || 5020
var autoCreate = gateway.json.autoCreate !== false && gateway.json.autoCreate !== 'false'
function publish(name, value){
values[name] = value
peers().emit('newValue', name, value, value + '', new Date())
}
function parse(text){ var n = Number(text); return text !== '' && !isNaN(n) ? n : text }
function handle(line, reply){
var m = /^(GET|SET|LIST)\b\s*(\S*)\s*(.*)$/i.exec(line.trim())
if(!m) return reply('ERR unknown command')
var cmd = m[1].toUpperCase(), name = '%line:' + m[2]
if(cmd == 'LIST') return reply(Object.keys(known).map(function(n){ return n.slice(6) }).concat(['END']).join('\n'))
if(!m[2]) return reply('ERR missing name')
if(cmd == 'GET') return reply(known[name] ? m[2] + '=' + (values[name] == null ? '' : values[name]) : 'ERR unknown ' + m[2])
var value = parse(m[3]) // SET
if(known[name]){ publish(name, value); return reply('OK') }
if(!autoCreate) return reply('ERR unknown ' + m[2])
known[name] = true
gws.insertAddress({name : name, description : 'created by SET', json : {datatype : typeof value == 'number' ? 'number' : 'string'}}, function(err){
if(err){ delete known[name]; return reply('ERR ' + err) }
publish(name, value)
reply('OK')
})
}
function listen(){
server = net.createServer(function(socket){
var buffer = ''
clients.push(socket)
socket.setEncoding('utf8')
socket.on('data', function(data){
buffer += data
var lines = buffer.split('\n')
buffer = lines.pop()
lines.forEach(function(l){ if(l.trim()) handle(l, function(r){ socket.write(r + '\n') }) })
})
socket.on('error', function(){})
socket.on('close', function(){ clients.splice(clients.indexOf(socket), 1) })
})
// port already used...: no 'connect', the gateway restarts the driver
server.on('error', function(e){ console.error('cannot listen on TCP port ' + port + ' : ' + e.message) })
server.listen(port, function(){
console.info('listening on TCP port ' + port)
peers().emit('connect')
peers().emit('ready')
})
}
methods.connect = function(callback){
peers('supervision').require('gateways', function(err, lib){
if(err) return console.error('gateways library unavailable', err)
gws = lib
gws.getAddressesByGateway(gateway.id, function(err, addresses){
;(addresses || []).forEach(function(a){ known[a.name] = true })
gws.on('addressInsertedGw ' + gateway.id, function(a){ known[a.name] = true })
gws.on('addressDeletedGw ' + gateway.id, function(a){ delete known[a.name]; delete values[a.name] })
// the last values kept by the box: GET answers right after a restart
var names = Object.keys(known), left = names.length
if(!left) return listen()
names.forEach(function(n){
gws.getLastValue(n, function(err, v){
if(!err && v != null) values[n] = v
if(--left == 0) listen()
})
})
})
})
if(callback) callback()
}
methods.read = function(name, callback){ callback(null, values[name] === undefined ? null : values[name]) }
methods.write = function(name, value, callback){ publish(name, value); callback() }
methods.acceptsRead = function(name, callback){ callback(null, /^%line:/.test(name)) }
methods.acceptsWrite = function(name, value, callback){ callback(null, /^%line:/.test(name)) }
methods.shutdown = function(callback){
clients.forEach(function(s){ s.destroy() })
if(server) server.close()
callback()
}
return methods
}
Schema code:
exports.schema = {
name : 'Line server',
regex : /^%line:/,
container : {network : 'bridge', publish : ['json.port/tcp']}, // a server: the port of the field « TCP port » is published
locales : {
'LINE_PORT' : {'en' : "TCP port the third-party system connects to.", 'fr' : "Port TCP auquel le système tiers se connecte.", 'de' : "TCP-Port, mit dem sich das Fremdsystem verbindet."},
'LINE_AUTO' : {'en' : "SET of an unknown name creates the address.", 'fr' : "Un SET d'un nom inconnu crée l'adresse.", 'de' : "Ein SET mit unbekanntem Namen legt die Adresse an."}
},
getDefaultGatewayOptions : function(gateway){
return {name : '', description : '', json : {port : 5020, autoCreate : true}}.deepExtend(gateway || {})
},
getGatewayForm : function(gateway, form){
var schema = this, o = this.getDefaultGatewayOptions(gateway)
return ['name', 'description', 'json.port', 'json.autoCreate'].map(function(key){
return schema.getGatewayField(key, key.indexOf('json.') == 0 ? o.json[key.slice(5)] : o[key])
})
},
getGatewayField : function(key, value){
var f = {
'name' : {nodeType : 'Text', label : 'Name'},
'description' : {nodeType : 'Text', label : 'Description'},
'json.port' : {nodeType : 'Port', label : 'TCP port', helper : 'LINE_PORT'},
'json.autoCreate' : {nodeType : 'Checkbox', label : 'Create addresses on SET', helper : 'LINE_AUTO'}
}[key]
if(!f) return
var out = {name : key}
for(var k in f) out[k] = f[k]
if(value !== undefined) out.value = value
return out
}
}
The port is open on every interface of the device, without authentication: use it on a trusted network, and see Securing the device.
Two meters answer the same JSON at two addresses:
http://192.168.1.50/api/status.#<id> Meter 1, save, reopen it, and set URL to http://192.168.1.51/api/status.Each gateway has its own addresses (%rest:power.active exists in both) and its own container. A correction of the code of Meter 1 restarts Meter 2 with the new code. The json of Meter 2:
{
"codeFrom": "12",
"url": "http://192.168.1.51/api/status",
"period": 60,
"autoCreate": true,
"container": {"network": "bridge", "sftp": false, "ftp": false, "publish": "", "guest": false}
}
The code below needs a library units. Without it, the driver logs library « units » not found: upload it to Files › node_modules/units, then restart the gateway and does not connect.
In the Files tab, click New folder... and create node_modules; right-click it, choose New folder here... and create units.
Right-click units, choose Upload here... and upload a file index.js that contains:
exports.toFahrenheit = function(c){ return Math.round((c * 9 / 5 + 32) * 10) / 10 }
Restart the gateway. It connects and creates %calc:celsius and %calc:fahrenheit.
Write 20 to %calc:celsius: %calc:fahrenheit becomes 68.
A library from npm works the same way when it is pure JavaScript: copy its folder and those of its dependencies (download them on a computer with npm install, then upload the node_modules folder).
Driver code (no schema needed, no network):
// Uses a library uploaded to the Files tab: /data/files/node_modules/units/index.js
// Writing a temperature in °C to %calc:celsius publishes it in °F on %calc:fahrenheit.
exports.regexs = [/^%calc:/]
exports.process = function(console, gateway, peers, onUpdate){
var methods = {}, values = {}, units = null
function publish(name, value){
values[name] = value
peers().emit('newValue', name, value, value + '', new Date())
}
methods.connect = function(callback){
try{
units = require('units') // looked up in /data/files/node_modules first
}catch(e){
console.error('library « units » not found: upload it to Files › node_modules/units, then restart the gateway')
return callback && callback() // no 'connect': the gateway restarts the driver later
}
peers('supervision').require('gateways', function(err, gws){
if(err) return console.error('gateways library unavailable', err)
gws.getAddressesByGateway(gateway.id, function(err, addresses){
var have = {}
;(addresses || []).forEach(function(a){ have[a.name] = true })
var wanted = [
{name : '%calc:celsius', description : 'temperature in °C (write)', json : {datatype : 'number'}},
{name : '%calc:fahrenheit', description : 'the same in °F', json : {datatype : 'number'}}
].filter(function(a){ return !have[a.name] })
var left = wanted.length
function start(){ peers().emit('connect'); peers().emit('ready') }
if(!left) return start()
wanted.forEach(function(a){ gws.insertAddress(a, function(){ if(--left == 0) start() }) })
})
})
if(callback) callback()
}
methods.read = function(name, callback){ callback(null, values[name] === undefined ? null : values[name]) }
methods.write = function(name, value, callback){
if(name != '%calc:celsius') return callback('read only : ' + name)
publish('%calc:celsius', value)
publish('%calc:fahrenheit', units.toFahrenheit(Number(value)))
callback()
}
methods.acceptsRead = function(name, callback){ callback(null, /^%calc:/.test(name)) }
methods.acceptsWrite = function(name, value, callback){ callback(null, name == '%calc:celsius') }
methods.shutdown = function(callback){ callback() }
return methods
}
| Symptom | Cause | What to do |
|---|---|---|
| Programmable driver is missing from Gateway driver | No docker on the device, or Windows. | Use a Linux device with docker. |
Gateway stays red; log no valid license for the programmable driver (feature ports 2628/9779 absent) - driver idle |
No Full licence on the device: the driver is only available with this bundle. | Contact support@weble.ch. |
Log no driver code : paste a driver in the gateway's « Driver code » tab |
The Driver code tab is empty. | Paste a driver, or set Driver from. |
Log driver code does not compile: Error: Cannot find module 'modbus-serial' |
A library required at the top of the code is missing. | Upload it to /data/files/node_modules (section 5.5), or require it inside connect with a clear message. |
Log driver code must define exports.process(console, gateway, peers, onUpdate) |
The code is not a driver. | Start from the example driver. |
Gateway restarts again and again; log runtime keeps dying (7 restarts in 5 min), restarting driver |
The code stops with an error. | Read the lines above it in the log (UNCAUGHT ...). |
| Gateway stays orange (CONNECTING), then restarts | The code never emits connect. |
Emit connect within 30 s, or extendConnect every 15 s while waiting. |
Log poll failed : getaddrinfo ENOTFOUND <host>, or EAI_AGAIN |
No network: the schema declares no container, or network : 'none'. |
Declare container : {network : 'bridge'} and save the gateway again. |
Log network 'host' requested without the administrator authorization (allowHostNetwork) : isolated network (bridge) used |
The schema asks for the network of the device. | Tick Box network without isolation if the driver needs broadcast. |
| A client cannot connect to the server of the driver | The port is not published, or not the one of the form. | Declare publish : ['json.port/tcp'] and save the gateway again. |
Log module '<name>' is not available to a programmable driver |
The code requires a module other than gateways and system. |
See section 4.3. |
Log <method> is not implemented by this driver |
The device calls a method the code does not return. | Add the method to the object returned by exports.process. |
| A new extra method is not found | It is published by an automatic restart, at most once every 5 minutes. | Restart the gateway. |
Log gateway #12 itself uses the driver of #7 : point to the gateway that holds the code |
Driver from points to a gateway that uses Driver from itself. | Choose the gateway that holds the code. |
To read the log of the driver: right-click the gateway and choose Logs (see Logs and diagnostics). Every line written by your code starts with [runtime].
npm and no package download in the container: libraries are uploaded to /data/files/node_modules.requireCompiled).
insertGateway, callGatewayMethod.