记录《用于物联网Arduino 项目开发实用案例解析》第五章 物联网模式:实时客户端的实践过程
一、Arduino 部分
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
//1.网络连接所需变量及函数
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress staticIP(192, 168, 31, 159);
EthernetClient client;
void connectToInternet()
{
if (Ethernet.begin(mac) == 0)
{
Serial.print("[ERROR] Failed to Configure Ethernet using DHCP");
Ethernet.begin(mac, staticIP);
}
delay(1000);
Serial.println("[INFO] Connection Successsful");
Serial.print("");
printConnectionInformation();
Serial.println("-------------------------");
Serial.println("");
}
void printConnectionInformation()
{
Serial.print("[INFO] IP Address: ");
Serial.println(Ethernet.localIP());
Serial.print("[INFO] Subnet Mask: ");
Serial.println(Ethernet.subnetMask());
Serial.print("[INFO] Gateway: ");
Serial.println(Ethernet.gatewayIP());
Serial.print("[INFO] DNS: ");
Serial.println(Ethernet.dnsServerIP());
}
//2.MQTT数据发布
char server[] = {"iot.eclipse.org"};
int port = 1883;
char topic[] = {"codifythings/intrusiondetection"};
void callbace(char* topic, byte*payload, unsigned int length)
{ }
PubSubClient pubSubClient(server, port, 0, client);
void publishSensorData()
{
Serial.println("[INFO] Connecting to MQTT Broker");
if (pubSubClient.connect("cumtzdArduinoIoTClient"))
{
Serial.println("[INFO] Connection to MQTT Broker Successful");
} else {
Serial.println("[INFO] Connection to MQTT Broker Failed");
}
if (pubSubClient.connected())
{
Serial.println("[INFO] Publishing to MQTT Broker");
pubSubClient.publish(topic, "Intrusion Detected");
Serial.println("[INFO] Publish to MQTT Broker Complete");
} else {
Serial.println("[ERROR] Publish to MQTT Broker Failed");
}
pubSubClient.disconnect();
}
//3.读取传感器数据变量及函数
int calibrationTime = 30;
long unsigned int lowIn;
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int pirpin = 3;
void calibrateSensor()
{
pinMode(pirpin, INPU