Created
June 3, 2019 07:26
-
-
Save AlexDoanTB/088c9e305e301c446e1ef71d53e10308 to your computer and use it in GitHub Desktop.
The Encoder function of simulated two-way RPC call via MQTT Integration from ThingsBoard tutorial
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** Decoder **/ | |
| // decode payload to string | |
| var payloadStr = decodeToString(payload); | |
| var data = JSON.parse(payloadStr); | |
| var topicPattern = 'tb/mqtt-integration-guide/sensors/(.+?)/.*'; | |
| var deviceName = metadata.topic.match(topicPattern)[1]; | |
| // decode payload to JSON | |
| var deviceType = 'sensor'; | |
| // Result object with device attributes/telemetry data | |
| var telemetry; | |
| if (metadata.topic.endsWith('/temperature')) { | |
| // Transform the incoming data as before | |
| telemetry = getTemperatureTelemetry(data); | |
| } else if (metadata.topic.endsWith('/rx/response')) { | |
| // Get the input value as is | |
| telemetry = data; | |
| } | |
| var result = { | |
| deviceName: deviceName, | |
| deviceType: deviceType, | |
| attributes: { | |
| integrationName: metadata['integrationName'], | |
| }, | |
| telemetry: telemetry | |
| }; | |
| /** Helper functions **/ | |
| function getTemperatureTelemetry(data) { | |
| return {temperature: data.value} | |
| } | |
| function decodeToString(payload) { | |
| return String.fromCharCode.apply(String, payload); | |
| } | |
| function decodeToJson(payload) { | |
| // covert payload to string. | |
| var str = decodeToString(payload); | |
| // parse string to JSON | |
| var data = JSON.parse(str); | |
| return data; | |
| } | |
| return result; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment