我正在尝试使用node.js coap package模拟LwM2M客户端节点。我在我的Raspberry Pi 3上运行并监听端口5555
的LwM2M服务器。
目前我所做的就是向lo
(环回)接口发送UDP数据包。 (但它被封装在另一个UDP数据包中,其源和目的地为00:00:00:00:00:00,但是现在对我来说并不重要。)
const coap = require('../') // Script is located inside package examples directory
const endpointClientName = 'someSensor'
const lifetime = '600'
const version = '1.0'
const binding = 'UQ'
let bodyString = '?ep=' + endpointClientName + '<=' + lifetime + '&lwm2m=' + version + '&b=' + binding;
let responseBody = '';
let options = {
host : 'fd72:cafe:face:0:fade:deaf:1234:5678',
port : 5555,
pathname : "/rd",
method : 'POST',
confirmable : 'true',
options : {
'Accept' : 'application/json'
}
};
let request = coap.request(options);
request.on('response', function (response) {
response.on('data', function () {
responseBody += response.payload.toString();
});
response.on('end', function () {
if (response.code == '2.01') {
console.log('[coap] device registered.');
var obj = JSON.parse(responseBody);
console.log('[coap] responseBody', obj);
} else {
console.log('[coap] coap response.code=' + response.code);
}
});
});
request.write(bodyString);
request.end();
上面的代码生成包含数据的UDP数据包:
Data (50 bytes)
Data: 44021dff8ea487ebb272646132ff3f65703d736f6d655365...
[Length: 50]
以下数据从wireshark粘贴为十六进制转储
0000 44 02 1d ff 8e a4 87 eb b2 72 64 61 32 ff 3f 65
0010 70 3d 73 6f 6d 65 53 65 6e 73 6f 72 26 6c 74 3d
0020 36 30 30 26 6c 77 6d 32 6d 3d 31 2e 30 26 62 3d
0030 55 51
但是我期待wireshark将数据包显示为CoAP数据包,其中包含分成几个部分的数据包:
Opt Name: #1: Uri-Path: rd
Opt Name: #2: Uri-Query: ep=someSensor
Opt Name: #3: Uri-Query: lt=600
Opt Name: #4: Uri-Query: lwm2m=1.0
Opt Name: #5: Uri-Query: b=UQ
我做错了什么?也许我设置错误的选项?我注意到有些人发送请求来解决coap://localhost:port/path
,但是我没有通过其他方式取得更好的结果。
答案 0 :(得分:0)
整个问题是lifetime
和lwm2m
版本等选项都在数据包正文中,但必须在query
中进行描述:
查询 :查询字符串。默认为&#39;&#39;。不应包括路径,例如
'a=b&c=d'
注册设备后,响应不是json格式,所有信息都不在响应体中,但在响应选项中:
<强> message.options 强>
所有CoAP选项,由CoAP-packet解析。
除
'Content-Format'
外,所有选项均为二进制格式,'Accept'
和'ETag'
。请参阅registerOption()
以了解如何注册 更多。有关所有可能的选项,请参阅spec。
话虽如此,通过稍微修改代码来解决问题:
const coap = require('../') // Script is located inside package examples directory
const serverAddress = 'fd72:cafe:face:0:fade:deaf:1234:5678'
const serverPort = 5555
const endpointClientName = 'someSensor'
const lifetime = '600'
const version = '1.0'
const binding = 'UQ'
const uriQuery = 'ep=' + endpointClientName + '<=' + lifetime + '&lwm2m=' + version + '&b=' + binding;
const clientResources = '/1/0'
let options = {
host : serverAddress,
port : serverPort,
pathname : "/rd",
method : 'POST',
confirmable : 'true',
query : uriQuery,
};
let request = coap.request(options);
request.on('response', function (response) {
console.log('[coap] coap response.code = ' + response.code);
console.log('[coap] coap response.options = ' + response.options);
});
request.write(clientResources);
request.end();