【发布时间】:2019-02-06 08:13:16
【问题描述】:
我通过 nrf24 无线电链路将使用 ArduinoJSON 构建的有效 JSON 对象发送到运行带有库 https://github.com/natevw/node-nrf 的 RaspberryPi 的 RaspberryPi。 node.js 服务器接收数据似乎没有问题。但由于某种原因,我不能 JSON.parse() 对象(或缓冲区?)没有得到SyntaxError: Unexpected token in JSON at position ...
由于某种原因,node-nrf 库向后接收数据,所以我需要用Array.prototype.reverse.call(d) 反转字节顺序,然后用console.log(d.toString()) 反转字节顺序,一切看起来都很好。在这种情况下,控制台获得Got data: [{"key":"a1","value":150}]。此时,缓冲区的内容类似于:Buffer 5b 7b 22 6b 65 79 22 3a 22 61 31 22 2c 22 76 61 6c 75 65 22 3a 31 35 30 7d 5d 00 00 00 00 00 00。我猜这些是 nrf24 缓冲区包含的实际 32 个字节。
但是,当代码到达 JSON.parse() 调用时,我得到SyntaxError: Unexpected token in JSON at position 26。这是我的对象数据在缓冲区中实际结束的位置。
我也尝试过 .toJSON() 和 JSON.stringify() ,但实际上无法获得合适的对象来使用(即 obj.key、obj.value)。它只返回 undefined 属性。在我看来,当它到达对象的末尾时解析失败。我还尝试将缓冲区大小与消息的实际大小相匹配,以查看解析是否会成功!
我可能对缓冲区、流、管道和对象的概念很困惑……我做错了什么?
我需要想法(或修复!)
node.js 中在接收端运行的代码:
var nrf = NRF24.connect(spiDev, cePin, irqPin);
nrf.printDetails();
nrf.channel(0x4c).transmitPower('PA_MIN').dataRate('1Mbps').crcBytes(2).autoRetransmit({count:15, delay:4000}).begin(function () {
var rx = nrf.openPipe('rx', pipes[0]);
rx.on('data', d => {
let obj = Array.prototype.reverse.call(d);
try {
console.log("Got data: ", d.toString());
console.log(obj);
obj = JSON.parse(obj);
console.log(obj);
} catch (err) {
console.error(err)
}
});
});
我认为问题不在于形成 JSON 消息。但作为参考,这是在 Arduino 上运行的代码:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <ArduinoJson.h>
const uint64_t addresses[5] = {0x65646f4e32LL,0x65646f4e31LL} ;
RF24 radio(7,8);
char output[32];
void setup()
{
Serial.begin(115200);
radio.begin();
radio.setAutoAck(true);
radio.setDataRate(RF24_1MBPS);
radio.enableDynamicPayloads();
radio.setCRCLength(RF24_CRC_16);
radio.setChannel(0x4c);
radio.setPALevel(RF24_PA_MAX);
radio.openWritingPipe(addresses[0]);
}
void loop()
{
const int capacity = JSON_ARRAY_SIZE(2) + 2*JSON_OBJECT_SIZE(2);
StaticJsonBuffer<capacity> jb;
JsonArray& arr = jb.createArray();
JsonObject& obj1 = jb.createObject();
obj1["key"] = "a1";
obj1["value"] = analogRead(A1);
arr.add(obj1);
arr.printTo(output);
bool ok = radio.write(&output, sizeof(output));
arr.printTo(Serial);
Serial.print(ok);
delay(1000);
}
【问题讨论】: