Este tema proporciona una plantilla de script en PHP y un script de ejemplo que puede usar para analizar sintácticamente los datos enviados a temas personalizados.
Plantilla del script
Para analizar sintácticamente los datos, escriba un script en PHP con base en la siguiente plantilla:
<?php
/**
* Convert the data that is sent by a device to a custom topic to JSON data when the device submits data to IoT Platform.
* $topic: the input parameter that specifies the topic to which the device sends messages. The value is a string.
* $rawData: the input parameter. The value is an array of integers.
* $jsonObj: an output parameter. The value is a JSON object that indicates an association array. The value of each key must be a string that is not a numeric string such as "10". Key values cannot be empty.
*/
function transformPayload($topic, $rawData)
{
$jsonObj = array();
return $jsonObj;
}
?>
Consideraciones para escribir el script
No use variables globales ni estáticas, ya que los resultados podrían ser inconsistentes.
En el script, procese los datos mediante la operación de complemento a dos. El rango de complemento para los valores entre [-128,127] es [0,255]. Por ejemplo, el complemento de -1 es 255 en formato decimal.
El parámetro de entrada de la función transformPayload es un arreglo de enteros. Use
0xFFen la operación AND bit a bit para obtener el complemento. El resultado devuelto es un arreglo asociativo. Cada valor de key debe contener caracteres que no formen un arreglo. Por ejemplo, si un valor de key es "10", el arreglo de PHP recupera el entero 10.El entorno de ejecución de PHP es muy estricto con el manejo de excepciones. Si ocurre un error, se lanza una excepción y el código posterior no se ejecuta. Para garantizar la solidez del código, capture y procese las excepciones.
Script de ejemplo
El siguiente script de ejemplo solo analiza sintácticamente los mensajes enviados a temas personalizados. Si establece el parámetro
Data Type
del producto como
Custom
, también debe escribir un script para analizar sintácticamente los mensajes de Thing Specification Language (TSL). Para más información, consulte
Submit a TSL model message parsing script
.
Para obtener información sobre los custom data formats, consulte Create a product.
<?php
/*
Sample data
Use the following custom topic to submit data:
/user/update.
Input:
topic: /${productKey}/${deviceName}/user/update
bytes: 0x000000000100320100000000
Output:
{
"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;
}