PHP script examples
Updated at:
This topic provides PHP templates and examples of data parsing scripts for Thing Specification Language models.
Script template
You can use this PHP script template to write your data parsing script.
Note This template applies only to products for which the Data Format is set to Pass-through/Custom.
<?php
/**
* Transforms data from the Alink protocol into a format that a device can recognize.
* IoT Platform calls this function when sending data to the device.
* Input parameter: $jsonObj, an associative array.
* Response parameter: $rawData, a regular array. The array elements must be integers from 0 to 255. The array cannot be empty.
*/
function protocolToRawData($jsonObj)
{
$rawData = array();
return $rawData;
}
/**
* Transforms data from a device's custom format into the Alink protocol format.
* IoT Platform calls this function when the device reports data.
* Input parameter: $rawData, a regular array with integer elements.
* Response parameter: $jsonObj, an associative array. The keys of the associative array must be English strings and cannot be numeric strings such as "10". The array cannot be empty.
*/
function rawDataToProtocol($rawData)
{
$jsonObj = array();
return $jsonObj;
}
/**
* Transforms data from a device's custom topic into JSON format.
* IoT Platform calls this function when the device reports data.
* Input parameter: $topic, a string that specifies the topic of the message reported by the device.
* Input parameter: $rawData, a regular array with integer elements.
* Response parameter: $jsonObj, an associative array. The keys of the associative array must be English strings and cannot be numeric strings such as "10". The array cannot be empty.
*/
function transformPayload($topic, $rawData)
{
$jsonObj = array();
return $jsonObj;
}
Scripting notes
- Avoid using global or static variables. This can cause inconsistent execution results.
- The script processes data using two's complement. The two's complement for the range [-128, 127] is [0, 255]. For example, the two's complement of -1 is 255 in decimal.
- The input parameter of the rawDataToProtocol function, which parses data reported by a device, is an integer array. Perform an AND operation with
0xFFto obtain the corresponding two's complement. The function returns an associative array. The key must contain non-numeric characters. For example, if the array key is "10", the PHP array interprets this as the integer 10. - The protocolToRawData function, which parses data sent from the IoT Platform, returns a regular PHP array. The array elements must be integers from 0 to 255.
- The input parameter of the transformPayload function, which parses custom protocols, is an integer array. Perform an AND operation with
0xFFto obtain the corresponding two's complement. The function returns an associative array. The key must contain non-numeric characters. For example, if the array key is "10", the PHP array interprets this as the integer 10. - The PHP execution environment is strict about exception handling. If an error occurs, an exception is thrown, and the subsequent code is not executed. To ensure code robustness, catch and handle exceptions.
Script example
Data parsing example for a Thing Specification Language modelThe following script is based on the defined properties and communication protocols.
<?php
/*
Sample data:
Data reported by the device
Input parameter ->
0x0000000001003201
Output result ->
{"method":"thing.event.property.post","id":"1","params":{"prop_int16":50,"prop_bool":1},"version":"1.0"}
Response to property settings
Input parameter ->
0x0300223344c8
Output result ->
{"code":"200","id":"2241348","version":"1.0"}
*/
function rawDataToProtocol($bytes)
{
$data = [];
$length = count($bytes);
for ($i = 0; $i < $length; $i++) {
$data[$i] = $bytes[$i] & 0xff;
}
$jsonMap = [];
$fHead = $data[0]; // command
if ($fHead == 0x00) {
$jsonMap['method'] = 'thing.event.property.post'; // Alink JSON format, topic for reporting properties
$jsonMap['version'] = '1.0'; // Alink JSON format, fixed field for the protocol version number
$jsonMap['id'] = '' . getInt32($data, 1); // Alink JSON format, ID of this request
$params = [];
$params['prop_int16'] = getInt16($data, 5); // Corresponds to the prop_int16 property of the product
$params['prop_bool'] = $data[7]; // Corresponds to the prop_bool property of the product
$jsonMap['params'] = $params; // Alink JSON format, standard params field
} else if ($fHead == 0x03) {
$jsonMap['version'] = '1.0'; // Alink JSON format, fixed field for the protocol version number
$jsonMap['id'] = '' . getInt32($data, 1); // Alink JSON format, ID of this request
$jsonMap['code'] = getInt8($data, 5);
}
return $jsonMap;
}
/*
Sample data:
Property settings
Input parameter ->
{"method":"thing.service.property.set","id":"12345","version":"1.0","params":{"prop_int16":333, "prop_bool":1}}
Output result ->
0x013039014d01
Response to data reported by the device
Input data ->
{"method":"thing.event.property.post","id":"12345","version":"1.0","code":200,"data":{}}
Output result ->
0x023039c8
*/
function protocolToRawData($json)
{
$method = $json['method'];
$id = $json['id'];
$version = $json['version'];
$payloadArray = [];
if ($method == 'thing.service.property.set') // Set properties
{
$params = $json['params'];
$prop_int16 = $params['prop_int16'];
$prop_bool = $params['prop_bool'];
// Concatenate rawData in the custom protocol format
$payloadArray = concat($payloadArray, hexStringToByteArray(toHex(0x01)));// command field
$payloadArray = concat($payloadArray, hexStringToByteArray(toHex(intval($id)))); // Alink JSON format 'id'
$payloadArray = concat($payloadArray, hexStringToByteArray(toHex($prop_int16))); // Value of the 'prop_int16' property
$payloadArray = concat($payloadArray, hexStringToByteArray(toHex($prop_bool))); // Value of the 'prop_bool' property
} else if ($method == 'thing.event.property.post') { // Response to data reported by the device
$code = $json['code'];
$payloadArray = concat($payloadArray, hexStringToByteArray(toHex(0x02))); // command field
$payloadArray = concat($payloadArray, hexStringToByteArray(toHex(intval($id)))); // Alink JSON format 'id'
$payloadArray = concat($payloadArray, hexStringToByteArray(toHex($code)));
} else { // Unknown command. Some commands are not processed.
$code = $json['code'];
$payloadArray = concat($payloadArray, hexStringToByteArray(toHex(0xff))); // command field
$payloadArray = concat($payloadArray, hexStringToByteArray(toHex(intval($id)))); // Alink JSON format 'id'
$payloadArray = concat($payloadArray, hexStringToByteArray(toHex($code)));
}
return $payloadArray;
}
/*
Sample data
Data is reported to the custom topic /user/update
Input parameters: topic: /{productKey}/{deviceName}/user/update and bytes: 0x000000000100320100000000
Output parameters:
{
"prop_float": 0,
"prop_int16": 50,
"prop_bool": 1,
"topic": "/{productKey}/{deviceName}/user/update"
}
*/
function transformPayload($topic, $bytes)
{
$data = array();
$length = count($bytes);
for ($i = 0; $i < $length; $i++) {
$data[$i] = $bytes[$i] & 0xff;
}
$jsonMap = array();
if (strpos($topic, '/user/update/error') !== false) {
$jsonMap['topic'] = $topic;
$jsonMap['errorCode'] = getInt8($data, 0);
} else if (strpos($topic, '/user/update') !== false) {
$jsonMap['topic'] = $topic;
$jsonMap['prop_int16'] = getInt16($data, 5);
$jsonMap['prop_bool'] = $data[7];
}
return $jsonMap;
}
function getInt32($bytes, $index)
{
$array = array($bytes[$index], $bytes[$index + 1], $bytes[$index + 2], $bytes[$index + 3]);
return hexdec(byteArrayToHexString($array));
}
function getInt16($bytes, $index)
{
$array = array($bytes[$index], $bytes[$index + 1]);
return hexdec(byteArrayToHexString($array));
}
function getInt8($bytes, $index)
{
$array = array($bytes[$index]);
return hexdec(byteArrayToHexString($array));
}
function byteArrayToHexString($data)
{
$hexStr = '';
for ($i = 0; $i < count($data); $i++) {
$hexValue = dechex($data[$i]);
$tempHexStr = strval($hexValue);
if (strlen($tempHexStr) === 1) {
$hexStr = $hexStr . '0' . $tempHexStr;
} else {
$hexStr = $hexStr . $tempHexStr;
}
}
return $hexStr;
}
function hexStringToByteArray($hex)
{
$result = array();
$index = 0;
for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
$result[$index++] = hexdec($hex[$i] . $hex[$i + 1]);
}
return $result;
}
function concat($array, $data)
{
return array_merge($array, $data);
}
function toHex($data)
{
$var = dechex($data);
$length = strlen($var);
if ($length % 2 == 1) {
$var = '0' . $var;
}
return $var;
}
Is this page helpful?