This article shows how to let an external application call the gateway API through an MQTT broker: the application publishes a JSON request on one topic and receives the reply on another topic. Two routes connect the MQTT driver to the API driver; the first one filters what the application is allowed to call.
Checked against: firmware r9347. Licences: the API driver and the MQTT driver are licensed features (contact support@weble.ch). Level: integrator, basic JavaScript.
At the end of this article, an MQTT client can read gateways and addresses, read values and write values on the gateway, and nothing else.
You need:
api.mqtt. See MQTT to create it.mosquitto_pub / mosquitto_sub, connected to the same broker.The topics weble/api/request and weble/api/reply are examples: use the naming of your project.
Open the address table of the mqtt gateway and insert two addresses:
| Name | Datatype | Other settings | Role |
|---|---|---|---|
%mqtt:weble/api/request |
json |
QOS At least once (1) |
The application publishes its requests here. The gateway subscribes to it. |
%mqtt:weble/api/reply |
json |
QOS At least once (1), tick Publish only (no subscribe) |
The gateway publishes the replies here. |
With the json datatype, a request received as text is parsed into a JSON object before it reaches the route, and the reply object is published as JSON text.
Insert a route with these parameters (Routes describes each column):
| Parameter | Value |
|---|---|
| Name | MQTT to API |
| Type | value |
| Trigger | tick value only (untick status, refresh and gateway) |
| Source gateway | mqtt |
| Source address | %mqtt:weble/api/request |
| Source value | the function below |
| Destination gateway | api |
| Destination address | %api |
| Retry | never (hidden column, or the route popup) |
Unticking refresh and gateway matters: otherwise the last request received would be executed again each time the route restarts or a gateway reconnects (see Trigger). Retry never avoids sending a refused request again.
Paste this function in Source value:
function mqttToApi(value, src, dst, options){
// 1. accept only JSON objects that name a module and a method
if(!value || value.constructor.name != "Object" || !value.module || !value.method){
options.error("rejected request (module or method missing)", value)
return
}
// 2. only these module / method pairs may be called from MQTT
var permitted = {
gateways : { getGateways : 1, getGateway : 1, getAddress : 1, getAddressesByGateway : 1,
getLastValue : 1, readValue : 1, writeValue : 1 }
}
if(!permitted[value.module] || !permitted[value.module][value.method]){
options.error("rejected request " + value.module + "/" + value.method)
return
}
// 3. no multi requests and no stream replies over this channel
if(value.requests || value.stream){
options.error("rejected request (requests / stream not allowed)")
return
}
// 4. work on a copy, and prefix the id: the reply is emitted on %api/reply/mqtt
var req = JSON.parse(JSON.stringify(value))
req.id = "mqtt/" + String(req.id || "noid").replace(/\//g, "_")
return req
}
What the function does:
options.error), visible when you listen to the route.writeValue if the application must only read.mqtt/. The API driver then emits the reply on %api/reply/mqtt instead of %api/reply, with the original id (see Reply addresses and id prefixes). A / in the id of the application would create further reply addresses, so the function replaces it with _.The routing function runs on the gateway. If several applications use the API, give each one its own request topic, its own route and its own prefix (
mqtt-ems/,mqtt-scada/…): each one then receives only its own replies.
The first reply creates the address %api/reply/mqtt on the API gateway. To create the route before any reply, send one test request first (section 5), or type the name by hand in the route.
| Parameter | Value |
|---|---|
| Name | API to MQTT |
| Type | value |
| Trigger | tick value only |
| Source gateway | api |
| Source address | %api/reply/mqtt |
| Source value | (empty) |
| Destination gateway | mqtt |
| Destination address | %mqtt:weble/api/reply |
Subscribe your test client to weble/api/reply, then publish the following messages on weble/api/request. Replace bacnet¬%bac:local/analogValue:1 by an address of your gateway: the address key is <gateway name>¬<address name>, or just the address name if it is unique on the device. If your client cannot type ¬, write it \u00ac inside the JSON string.
Read a value on the field bus
{ "id": "r1", "module": "gateways", "method": "readValue", "address": "bacnet¬%bac:local/analogValue:1" }
Reply:
{ "id": "r1", "value": 21.5 }
Write a value
{ "id": "w1", "module": "gateways", "method": "writeValue", "address": "bacnet¬%bac:local/analogValue:1", "value": 22 }
Reply { "id": "w1" } on success, or { "id": "w1", "error": "invalid value" } if the driver refuses the value.
List the gateways
{ "id": "g1", "module": "gateways", "method": "getGateways" }
This reply is usually longer than 10 000 characters. The API driver then splits it into segments, published one after the other about 10 ms apart:
{ "id": "g1", "segment": 1, "total": 3, "value": "{\"id\":\"g1\",\"value\":{\"170\":{..." }
Concatenate the value strings in segment order, then parse the result as JSON. If your application cannot reassemble segments, set Segmentation to 0 on the API gateway; check then that your broker accepts messages of that size.
Check the result. In the address table of the api gateway, %api shows the last request (with the mqtt/ prefix) and %api/reply/mqtt the last reply. In the mqtt gateway, %mqtt:weble/api/reply shows the last published reply.
| Symptom | Cause and fix |
|---|---|
No reply at all, and %api does not change |
The route refused the request. Listen to the route MQTT to API: the log gives the reason (module or method missing, method not allowed). Check also that the request is valid JSON. |
%api does not change, the route listener shows a write-error such as missing parameter: address |
The API driver refused the request before calling the method: a parameter is missing or has the wrong type. No reply is emitted in this case. Fix the request (see the method in API driver). |
%api/reply/mqtt changes but nothing is published |
Check the route API to MQTT (source gateway api, destination gateway mqtt) and that the MQTT gateway is connected. |
Replies arrive on %api/reply instead of %api/reply/mqtt |
The request did not go through the function (another route writes to %api, or the function was not saved). |
The reply contains "error": "address not found" or similar |
The method was called: the error comes from the gateway itself. Check the address key. |
| The application receives truncated JSON | The reply is segmented: reassemble the segments, or set Segmentation to 0. |
subscribe, ackSubscribe…): add these methods to the list of the function and read Loggers module.options argument.