Created
May 31, 2019 05:47
-
-
Save AlexDoanTB/e4da723952acdd97eb0024493938202f to your computer and use it in GitHub Desktop.
Uplink decoder function for MQTT Integration to 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/(.+)/temperature'; | |
| var deviceName = metadata.topic.match(topicPattern)[1]; | |
| // decode payload to JSON | |
| var deviceType = 'sensor'; | |
| // Result object with device attributes/telemetry data | |
| var result = { | |
| deviceName: deviceName, | |
| deviceType: deviceType, | |
| attributes: { | |
| integrationName: metadata['integrationName'], | |
| }, | |
| telemetry: { | |
| temperature: data.value, | |
| } | |
| }; | |
| /** Helper functions **/ | |
| function decodeToString(payload) { | |
| return String.fromCharCode.apply(String, payload); | |
| } | |
| function decodeToJson(payload) { | |
| // convert 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