PHP阿里云物联网,PHP脚本示例
示例脚本说明 以下示例脚本仅用于解析自定义Topic数据。如果产品的数据格式为透传/自定义,还需编写物模型数据解析脚本。物模型数据解析脚本编写指导,请参见有关透传/自定义说明,请参见...
示例脚本
说明 以下示例脚本仅用于解析自定义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;
}
更多推荐
所有评论(0)