Here is the JavaScript code to decode the payload and format it into the TagoIO data object format
/*** Parses the payload and returns an array of data objects.** @param {string} hexPayload - The payload in hex to be parsed.* @returns {Array} An array of data objects extracted from the payload.*/function parsePayload(hexPayload) {const buffer = Buffer.from(hexPayload, "hex");const jsonString = buffer.toString("utf8");const jsonObject = JSON.parse(jsonString);const time = new Date().toISOString();const group = `${new Date().getTime()}-${Math.random().toString(36).substring(2, 5)}`;const data = [{ variable: "E", value: jsonObject.E, group, time },{ variable: "S", value: jsonObject.S, group, time },{ variable: "V", value: jsonObject.V, group, time },{ variable: "T", value: jsonObject.T, group, time },{ variable: "M", value: jsonObject.M, group, time },{ variable: "hash", value: jsonObject["#"], group, time }];return data;}// Handle Received Dataconst hexPayload = payload.find((x) => x.variable === "payload").value;if (hexPayload) {try {const parsedData = parsePayload(hexPayload);payload = parsedData;} catch (error) {// Print the error to the Live Inspector.// console.error(error);// Return the variable parse_error for debugging.payload = [{ variable: "parse_error", value: error.message }];}}
Explanation:
Buffer Conversion: The payload value is converted from a hexadecimal string to a buffer.
JSON Parsing: The buffer is converted to a UTF-8 string and then parsed as a JSON object.
Data Extraction: Each key-value pair in the JSON object is mapped to a TagoIO data object with a variable name, value, group, and time.
Payload Handling: The parsed data is assigned back to the payload variable.