本文提供PHP語言的自定義Topic消息解析腳本模板和示例。
腳本模板
PHP腳本模板,您可以基于以下模板編寫消息解析腳本。
<?php
/**
* 將設備自定義Topic消息數據轉換為JSON格式數據,設備上報數據到物聯網平臺時調用。
* 入參:$topic,字符串,設備上報消息的Topic。
* 入參:$rawData,普通數組,數組元素為整數。
* 出參:$jsonObj,關聯數組,關聯數組key取值為英文字符串不能是字符的數字如"10",不能為空。
*/
function transformPayload($topic, $rawData)
{
$jsonObj = array();
return $jsonObj;
}
?>
腳本編寫注意事項
- 請避免使用全局變量或者static變量,否則會造成執行結果不一致。
- 腳本中,處理數據采用補碼的方式, [-128, 127]補碼范圍為[0, 255]。例如,-1對應的補碼為255(10進制表示)。
- 自定義協議解析的函數(transformPayload)的入參為整型數組。需要通過
0xFF
進行與操作,獲取其對應的補碼。返回結果為關聯數組,要求key取值包含非數組字符(如數組key為“10”,PHP數組中會獲取到整數10)。 - PHP執行環境對于異常處理會很嚴格,如發生錯誤會直接拋出異常,后續代碼不會執行。保證代碼的健壯性,對于異常需要捕獲并進行處理。
示例腳本
說明 以下示例腳本僅用于解析自定義Topic消息。如果產品的數據格式為透傳/自定義,還需編寫物模型消息解析腳本。物模型消息解析腳本編寫指導,請參見提交物模型消息解析腳本。
有關透傳/自定義說明,請參見創建產品。
<?php
/*
示例數據
自定義Topic:
/user/update,上報數據。
輸入參數:
topic: /${productKey}/${deviceName}/user/update
bytes: 0x000000000100320100000000。
輸出參數:
{
"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;
}