使用 MQTT 通过 Websockets 从后端连接到 AWS IoT



我正在尝试从服务器端连接到 AWS IoT。我不想通过浏览器客户端连接到 AWS IoT。

为了提供更多上下文,我模拟了一个设备(目前只是一个浏览器客户端),该设备接受输入并通过 Websockets 将其发送到我的服务器。从那里,我想获取该输入,并通过 MQTT 通过 websockets 将其发送到 AWS IoT(或其他方式)。

我的客户端不可能直接通过 MQTT 通过 websocket,因为我的设备被限制为只能通过 Websocket 上的另一个协议进行通信。

把它想象成一个协议转换器,或者只是从一个套接字隧道接收到的消息并将其传递给另一个套接字。

(client)----通过 ws----> 发送消息 (服务器) ----使用 MQTT --->(AWS IOT) 发送消息

我希望这是有道理的。 我已经成功运行了不少示例(我的第一个代码片段连接到 test.mosquitto.org),并且拥有 mqttjs 和 AWS IoT 开发工具包。在这个阶段,我只是在努力使连接在我想如何使用它的上下文中正常工作。

任何建议或意见将不胜感激。

我的第一个代码片段是我目前正在尝试的(也是我认为最可行的)

var options = {
clientId : 1,
endpoint: 'xxxxxxxxxx.iot.xxxxxxxxxx.amazonaws.com',
accessKey: 'xxxxxxxxxx',
secretKey: 'xxxxxxxxxxxxxxxxxxxx',
regionName: 'xxxxxxxxxx',
debug: true
};

var client = _mqtt.connect('ws://xxxxxxxxxx.iot.xxxxxxxxxx.com', options);
//var client  = _mqtt.connect('mqtt://test.mosquitto.org');
client.on('connect', function () {
console.log("MQTT connected");
client.subscribe('testing')
client.publish('testing', 'Hello mqtt2')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})

这是我其他失败的尝试之一。至少这个提供了一个错误。

var device = awsIot.device({
keyPath: './certs/xxxxxxxxxx-private.pem.key',
certPath: './certs/xxxxxxxxxx-certificate.pem.crt',
caPath: './certs/root-CA.crt',
clientId: 1,
debug: true,
host: 'xxxxxxxxxx.iot.xxxxxxxxxx.amazonaws.com'
});
//
// Device is an instance returned by mqtt.Client(), see mqtt.js for full
// documentation.
//
device
.on('connect', function() {
console.log('connect');
device.subscribe('topic_1');
device.publish('topic_2', JSON.stringify({ test_data: 1}));
});
device
.on('message', function(topic, payload) {
console.log('message', topic, payload.toString());
});

这是输出/错误

{ keyPath: './certs/xxxxxxxxxx-private.pem.key',
certPath: './certs/xxxxxxxxxx-certificate.pem.crt',
caPath: './certs/root-CA.crt',
clientId: 1,
debug: true,
host: 'xxxxxxxxxx.iot.xxxxxxxxxx.amazonaws.com',
keepalive: 300,
username: '?SDK=JavaScript&Version=2.2.0',
reconnectPeriod: 1000,
fastDisconnectDetection: true,
resubscribe: false,
protocol: 'mqtts',
port: 8883,
key: <Buffer 2d 2d 2d 2d 2d 42 45 47 49 4e 20 52 53 41 20 50 52 49 56 41 54 45 20 4b 45 59 2d 2d 2d 2d 2d 0a 4d 49 49 45 70 41 49 42 41 41 4b 43 41 51 45 41 32 42 ... >,
cert: <Buffer 2d 2d 2d 2d 2d 42 45 47 49 4e 20 43 45 52 54 49 46 49 43 41 54 45 2d 2d 2d 2d 2d 0a 4d 49 49 44 57 54 43 43 41 6b 47 67 41 77 49 42 41 67 49 55 53 33 ... >,
ca: <Buffer 2d 2d 2d 2d 2d 42 45 47 49 4e 20 43 45 52 54 49 46 49 43 41 54 45 2d 2d 2d 2d 2d 0d 0a 4d 49 49 45 30 7a 43 43 41 37 75 67 41 77 49 42 41 67 49 51 47 ... >,
requestCert: true,
rejectUnauthorized: true }
attempting new mqtt connection...
net.js:617
throw new TypeError('invalid data');
^
TypeError: invalid data
at TLSSocket.Socket.write (net.js:617:11)

发现问题!

我得到了第一个建议的代码片段:

  • 客户端 ID 未封装在引号中
  • 我没有在 AWS IoT 控制台上向现有事物添加策略

我仍然很好奇我的第二次尝试是否可行,所以如果您有任何建议,请提供见解。

最新更新