当前位置:网站首页>Esp8266 building smart home system

Esp8266 building smart home system

2022-06-25 15:06:00 Knowledge first

One background

I always wanted to be a smart home monitoring system , It is hypocritical to say that there is no time , It's true that you can't afford to buy a server …, Later, I thought about intranet penetration , Use raspberry pie or pc Local running service program , I think it's too much trouble and I haven't done it , So people , If you don't want to do anything, you can find a thousand 、 Tenthousand excuses .

Why did you do it now ???

I am so stingy , It must be the money , Did you take on an outsourced project to do ? That must not be !

The reason is that I bought a foreign server as an agent recommended by my friend , Go online ( You'll see ), It's only a month 18 element ! Although the configuration is a little low , Enough for me .

I just wanted to , All the money has been paid , Just for surfing the Internet , That would be a waste , Why not install more service programs ?

In the spirit of economy , Recall the previous ideal of smart home , So say do it !… And then in the middle of the night 3 Some didn't go to bed , The next morning 9 Get up and write articles at !

It looks like going. , Finally, I chose the simple one MQTT agreement , Selected by the service program mosquitto.

MQTT Is a release based / Subscription mode message transfer protocol . It's lightweight 、 to open up 、 Simple , Easy to implement , Low communication bandwidth requirements . These characteristics make it important for machine to machine communication (M2M) And Internet of things applications (IoT) It's a good choice for .

Mosquitto Is an open source message broker , Realized MQTT Protocol version 3.1 and 3.1.1.Mosquitto Light weight , It is applicable to all devices from low-power single board computer to complete server .Mosquitto The project also provides for the implementation of MQTT Client's C Library and very popular mosquitto_pub and mosquitto_sub Command line MQTT client .

Remember the above MQTT agreement and mosquitto Service program .

Last , It occurred to me that , As long as you can connect to the proxy server , In this way, you can control the electrical appliances in your home anywhere in the world !!!

Two System composition and principle

Want to realize the remote monitoring of data , There should be three parts , terminal 、 Server side 、 client .

1、esp8266 End

The terminal needs to be checked (esp8266) monitor ,esp8266 The client not only needs to send data , You still need to receive it ( subscribe ) data , For example, the mobile phone controls the electric light in the home .
Data upload (publish): Continuously collect various sensor data sets , And then use MQTT Agreements are made at regular intervals publish To the server .
Data subscription (subscribe): stay publish Data interval , This time is devoted entirely to MQTT Monitor data .

The software I wrote is not smart enough , The type of sensor 、 The number must be determined when designing , Or leave space . If a new sensor is added later , You will need to modify the source code .
If you can follow up , Redesign esp8266 Software for , Then write an upper computer for setting esp8266 Interface and type of sensor . I wonder if there is any open source code for such a scheme , I guess there may be , After all, programmers are smart people ! Who doesn't have a brain , Ha ha ha ha ha ha ha …

Relationship system

 Insert picture description here

Two Preparation instructions

0、 Accumulation of knowledge

mqtt Novice tutorial :https://www.runoob.com/w3cnote/mqtt-intro.html

MQTT There are three identities in the agreement : Publisher (Publish)、 agent (Broker)( The server )、 subscriber (Subscribe).

below , We call the main data publisher as the acquisition terminal , The primary subscriber is called the client , An agent is called a server , Respectively introduced .

1、 Acquisition terminal

Acquisition terminal , That is, the sensor data acquisition end 、 Output control terminal , namely MCU terminal .MQTT The protocol is based on TCP Transmission of , Therefore, the single-chip microcomputer is required + Network module (W5500)+ Network cable connection ? No no no , Use esp32、esp8266 wifi Connect 、 Wireless transmission , Is it not fragrant ? I this esp32、8266 There are , although esp32 Better performance , But before esp8266 There is a hardware connection , And just can use , So use 8266 了 , After all, there is little difference between the two in programming .

Here's an explanation , I use it. arduino IDE Programming , Yes, you can download it directly MQTT Library ( Otherwise, software development will not be so fast )
arduino IDE download MQTT library , Click on the menu bar Tools -> Manage library options , Pop up the pop-up window below , Download according to the marked content .
explain , need “ Science and the Internet ” Download will be unimpeded , Otherwise, no response may be downloaded .
 Insert picture description here

Hardware connection diagram :
placeholder !!!

2、 Server side :

Server side , I installed CentOS 7, The service program is mosquitto,mosquitto It can also be said to be an agent , It helps you send messages from Publisher (published) Forwarding to Subscribers (subsription).

CentOS 7 install mosquitto: Direct use command :yum install mosquitto
Or refer to the link :https://blog.csdn.net/qq_34301871/article/details/93617204
mosquitto Use the tutorial :https://www.cnblogs.com/chen1-kerr/p/7258487.html

3、 client

The client monitors and collects terminal data , The client can be a mobile phone 、 The computer , Or other networking devices , It can also be esp8266, It is used to display the home status data or obtain the set status , But we usually only talk about PC End , The following describes the client software of each platform .
Because it's easier , The following software will not be used in the tutorial , Fumble for yourself , This is the fun of the damn techno .
Android Software : I use it MQTT Dash( Science and the Internet ,google Store downloaded , Have to say , There are still a lot of easy-to-use software , And there's no advertising for free )
 Insert picture description here
All the controls in the above figure can be edited and customized , For example, the light is green , Turn off the light and set it to gray , Fire smoke detected shows red, etc .

windows Software : MQTTX
windows At present, there is no graphical interface monitoring software that can be customized and edited ( Like Android above ).
The following software can only be used for debugging in the program development stage , After all, who wants to use this interface to view data .
 Insert picture description here
In fact, in my system design , The idea is to use qt Write a general editable graphical client software , As the figure below :
 Insert picture description here
Editable background , Then various terminals can be added and terminal pictures can be set , Mobile location 、 Set the terminal control size and other functions .
But the workload is not small , Work at ordinary times , Play games after work , No power .( After all, I am lazy )

Other platform clients
Other platforms such as linux, Not used . however MQTTX Support many platforms , You can download the corresponding software .
 Insert picture description here
Use... When developing windows Of MQTTX Software debugging is very good , When the system is almost complete , You can use your mobile phone to debug , After all, mobile phones are easy to carry .

Four software development

The code content is as follows :
1、wifi Connect , Only when the connection is successful will the execution continue .
2、 Initialize various sensors 、 And executive parts , Such as temperature and humidity 、 ultrasonic 、led etc. .
3、 Set up MQTT Subscriptions ( basis topic of conversation -Topic ), Used to listen for instructions sent by the client .
4、 Loop monitoring 、 send data .

esp8266 End code (arduino IDE Development ):

#include <ESP8266WiFi.h>
#include <Adafruit_NeoPixel.h>
#include <DHTesp.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

//====================================================================================
#if 1 //1: Use serial port to print out  0: Serial port output is prohibited 
  #define coutInit(x) Serial.begin(x)
  #define cout Serial.print
  #define coutln Serial.println
#else
  #define coutInit(x) 
  #define cout(x) 
  #define coutln(x)
#endif 
//====================================================================================
#define WLAN_SSID " Almost let you know wifi It's a name "
#define WLAN_PASS " Almost let you know wifi It's a password "
//====================================================================================
WiFiClient client;
#define AIO_SERVER "mosquitto Server address , It can be ip Address "
#define AIO_SERVERPORT 1883 // use 8883 for SSL
#define AIO_USERNAME "mosquitto Username , If you don't, just go to see mosquitto Use the tutorial "
#define AIO_KEY "mosquitto The user password of "
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

Adafruit_MQTT_Publish updataCount = Adafruit_MQTT_Publish(&mqtt,"esp_updataCount",0);
Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt,"esp_Rx_1",0);

Adafruit_MQTT_Publish pub_temp = Adafruit_MQTT_Publish(&mqtt,"esp_temp",0);
Adafruit_MQTT_Publish pub_hum = Adafruit_MQTT_Publish(&mqtt,"esp_hum",0);
Adafruit_MQTT_Publish pub_distance = Adafruit_MQTT_Publish(&mqtt,"esp_distance",0);
Adafruit_MQTT_Subscribe sub_led = Adafruit_MQTT_Subscribe(&mqtt,"esp_led",0);

//====================================================================================
void MQTT_connect(int reconnect = 0)     // In case of loss of connection, it will automatically reconnect 
{
    
  int8_t ret;
  if(!reconnect)
  {
    
    if (mqtt.connected()) 
      return;
  }

  cout("Connecting to MQTT... ");
  uint8_t retries = 20;  // Automatic reconnection 20 Time ,20 After that, it can not be connected to enter the dead cycle , Wait for the watchdog to restart 
  while ((ret = mqtt.connect()) != 0)   // connect will return 0 for connected
  {
     
       coutln(mqtt.connectErrorString(ret));
       coutln("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  
       retries--;
       if (retries == 0) 
       {
    
         while (1); 
       }
  }
  coutln("MQTT Connected!");
}
//==================================================================================== 
#define dhtPin 2
DHTesp dht;
float dht_temp;
float dht_hum;

void dht11Init()
{
    
  dht.setup(dhtPin, DHTesp::DHT11);
}
void getDHT11Data()
{
    
  TempAndHumidity dhtValues = dht.getTempAndHumidity();
  dht_temp = dhtValues.temperature;
  dht_hum = dhtValues.humidity;
}
//=======================================================================
#define trigPin 12
#define echoPin 13

void distanceInit()
{
    
  digitalWrite(trigPin, LOW);
  delayMicroseconds(1000);
  digitalWrite(trigPin, HIGH);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT);  // Sets the echoPin as an Input
}
float getDistance()
{
    
  digitalWrite(trigPin, LOW);  // Clears the trigPin
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);  // Sets the trigPin on HIGH state for 10 micro seconds
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH);  // Reads the echoPin, returns the sound wave travel time in microseconds
  float distance = duration*0.034/2;  // Calculating the distance
  return distance;
}

//=======================================================================
#define ledPIN 4 // Definition LED Lattice  IO

void RGB_LED_Init(void)
{
    
  pinMode(ledPIN, OUTPUT);      
}
void openLED()
{
    
  digitalWrite(ledPIN, HIGH);
}
void closeLED()
{
       
  digitalWrite(ledPIN, LOW);
}
//=======================================================================
void ledCallback(double led)
{
    
  cout(F("Get LED: "));
  coutln(led);
  if(led > 0.5)
    openLED();
  else
    closeLED();
}
void stringCallback(char *data, uint16_t len) {
    
  cout("Hey we're in a onoff callback, the button value is: ");
  coutln(data);
}

void setup() {
    
  coutInit(115200);
  delay(20);

  //=====  Connect wifi =====
  cout("\nConnecting to ");
  coutln(WLAN_SSID);
  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) 
  {
    
    delay(500);
    cout(".");
  }
  coutln();
  cout("WiFi connected,IP address: ");
  coutln(WiFi.localIP());

  //=====  Initialize various sensors  =====
  coutln("DHT11 initialization...");
  dht11Init();
  coutln("Ultrasonic initialization...");
  distanceInit();
  coutln("LED initialization...");
  RGB_LED_Init();
  
  //=====  Set up subscribe =====
  //mqtt.subscribe(&onoffbutton);
  sub_led.setCallback(ledCallback);
  mqtt.subscribe(&sub_led);
}


void loop() 
{
    
  MQTT_connect();
  mqtt.processPackets(5000);

  int succes_count = 0;   // Send success count , Used to judge the connection status ,MQTT_connect Function cannot judge for a short time .
  //=====  Send count  =====
  static unsigned int runCount;
  cout(F("Sending updataCount val ")); cout(runCount); cout("...");
  if (! updataCount.publish(runCount++))
  {
     
    coutln(F("Failed"));
  }
  else 
  {
    
    coutln(F("OK!"));
    succes_count ++;
  }
    
  //=====  Send temperature 、 humidity (DHT11) =====
  getDHT11Data();  // Get temperature and humidity 
  cout(F("Sending DHT11 - temp:"));
  cout(dht_temp);cout("...");
  if (! pub_temp.publish(dht_temp)) // Send temperature 
  {
    
    coutln(F("Failed"));
  }
  else 
  {
    
    coutln(F("OK!"));
    succes_count ++;
  }
    
  cout(F("Sending DHT11 - hum:"));
  cout(dht_hum);cout("...");
  if (! pub_hum.publish(dht_hum)) // Send humidity 
  {
    
    coutln(F("Failed"));
  }
  else 
  {
    
    coutln(F("OK!"));
    succes_count ++;
  }
  
  //=====  Sending distance  =====
  float distance = getDistance(); // Get the distance 
  cout(F("Sending distance:"));
  cout(distance);cout("...");
  if (! pub_distance.publish(distance))
  {
    
    coutln(F("Failed"));
  } 
  else 
  {
    
    coutln(F("OK!"));
    succes_count ++;
  }
  
  coutln(F("==========================="));
  
  //=====  Send failure processing method  =====
  static int sendFaildCount = 0;  // The number of consecutive total send failures 
  if(succes_count == 0) // Indicates that all sending failed 
  {
    
    sendFaildCount ++;
    if(sendFaildCount >= 3)
    {
    
      MQTT_connect(1);  // Forced reconnection 
      sendFaildCount = 0;
    }
  }
  else
    sendFaildCount = 0;
}
原网站

版权声明
本文为[Knowledge first]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200512308004.html