Использование протокола MQTT в «Умном доме». Часть 1 - Arduino
13 Oct 2017
local_offer
smarthouse
local_offer
mqtt
Отправка показаний температуры и влажности в MQTT
MQTT (Message Queue Telemetry Transport)
брокер.
Скетч для arduino:
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <dht.h>
// Update this to either the MAC address found on the sticker on your ethernet shield (newer shields)
// or a different random hexadecimal value (change at least the last four bytes)
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xFF };
char macstr[] = "deadbeeffeff";
// Note this next value is only used if you intend to test against a local MQTT server
byte localserver[] = { 192, 168, 0, 170 };
// Update this value to an appropriate open IP on your local network
byte ip[] = { 192, 168, 0, 179 };
byte gateway[] = { 192, 168, 0, 1 };
byte subnet[] = { 255, 255, 255, 0 };
char servername[]="quickstart.messaging.internetofthings.ibmcloud.com";
String clientName = String("d:quickstart:arduino:") + macstr;
String topicName = String("iot-2/evt/status/fmt/json");
DHT DHT11 = DHT();
float tempF = 0.0;
float tempC = 0.0;
float humidity = 0.0;
EthernetClient ethClient;
// Uncomment this next line and comment out the line after it to test against a local MQTT server
PubSubClient client(localserver, 1883, 0, ethClient);
//PubSubClient client(servername, 1883, 0, ethClient);
void setup()
{
// Start the ethernet client, open up serial port for debugging, and attach the DHT11 sensor
Ethernet.begin(mac, ip);
Serial.begin(9600);
DHT11.attach(A0);
}
void loop()
{
char clientStr[34];
clientName.toCharArray(clientStr,34);
char topicStr[26];
topicName.toCharArray(topicStr,26);
getData();
if (!client.connected()) {
Serial.print("Trying to connect to: ");
Serial.println(clientStr);
client.connect(clientStr);
}
if (client.connected() ) {
String json = buildJson();
char jsonStr[200];
json.toCharArray(jsonStr,200);
boolean pubresult = client.publish(topicStr,jsonStr);
Serial.print("attempt to send ");
Serial.println(jsonStr);
Serial.print("to ");
Serial.println(topicStr);
if (pubresult)
Serial.println("successfully sent");
else
Serial.println("unsuccessfully sent");
}
delay(60000);
}
String buildJson() {
String data = "{";
data+= "\"d\": {";
data+="\"myName\": \"Arduino DHT11\",";
data+="\"temperature (C)\": ";
data+=(int)tempC;
data+= ",";
data+="\"humidity\": ";
data+=(int)humidity;
data+="}";
data+="}";
return data;
}
void getData() {
DHT11.update();
switch (DHT11.getLastError()) {
case DHT_ERROR_OK:
Serial.println("Read OK");
humidity = (float)DHT11.getHumidityInt();
tempC = DHT11.getTemperatureInt();
tempF = tempC * 1.8 + 32;
break;
case DHT_ERROR_CHECKSUM_FAILURE:
Serial.println("Checksum error");
break;
case DHT_ERROR_READ_TIMEOUT:
Serial.println("Time out error");
break;
default:
Serial.println("Unknown error");
break;
}
}