在试着给http://mqtt.phodal.com/做一个简单的Arduino示例,找到了这个库https://github.com/knolleary/pubsubclient,果断试了试。
MQTT Arduino
开始之前
需要的东西有:
- Arduino
- Arduino Ethernet
- MQTT服务
假设我们已经满足了上面的条件。
Arduino Pubsubclient 示例
引用官方的示例
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
byte server[] = { 192, 168, 168, 78 }; // MQTT服务地址
byte ip[] = { 192, 168, 168, 250 }; // 设备IP
void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
}
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void setup()
{
Ethernet.begin(mac, ip);
if (client.connect("arduinoClient")) {
client.publish("outTopic","hello world");
client.subscribe("inTopic");
}
}
void loop()
{
client.loop();
}
运行,接着报了各种服务错误。。。
{ [Error: read ECONNRESET] code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
{ [Error: read ECONNRESET] code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
打开一看,发现是限定了传进来的格式要是JSON的。
于是:
client.publish("outTopic","{'hello': 'true'}");
It Works。
其他
这里的测试环境是在本地,不知何原因无法使用服务器,是否是因为DNS缓存?
或许您还需要下面的文章: