mqtt combined with slq soil detection system – can be used with 5g module to achieve wireless transmission

Table of Contents

Preface

mqtt configuration

Configuration of slq database

Code writing for esp8266

Writing python code

Various sensors cooperate with 2560 development board code

Schematic diagram


Foreword

In this project, after communicating with the 2560 through various sensors, it is sent to the 8266 through the serial port to achieve ultra-long-distance transmission, because the current SLQ database can only be transmitted through the LAN, which is usually not available in greenhouses, farms and other places. If you want to specifically configure wifi transmission, you can also use the lora module, and you can consider developing it later.

Before starting the project, you need to prepare the SGP30 carbon dioxide detection module, the DHT11 temperature and humidity detection module, and the photosensitive sensor. I directly use the photosensitive sensor read by ADC as the photosensitive sensor, as well as the soil moisture sensor. The development boards are esp8266 and mega2560 and the final product is probably as follows

There should be another 2560 in the middle but I haven’t plugged it in yet.

mqtt configuration

I use emqx for mqtt. The main reason is that emqx is free and can currently be transmitted through the public server of emqx. However, considering security issues, I still use a private server configured on emqx for development. First, enter the website EMQX: Scale distributed MQTT message server

You can try it out if you don’t have an account. Register one first.

After entering this interface

It all comes down to personal choice. I chose to use the free one and just open it for free.

I use emqx server in Hangzhou (Alibaba Cloud). It takes 2 minutes to open it for the first time.

For authentication on this interface, you can add the authentication account and password first, but you have to remember it yourself, which will be used later, and you need to add two authentication devices, one for esp8266 and one for python. Later, python will be used as mqtt to transfer to slq. Use an authentication

slq database configuration

slq I use Tencent Cloud’s database

I won’t go into too much details about the specific registration method of Tencent Cloud SLQ. You can refer to the following article for details. Currently, it is quite cost-effective for college students to activate this. I have directly activated it for a year. This wave is considered to be between Alibaba and Tencent. great combination(dog)

https://blog.csdn.net/qq_41188880/article/details/113876439

Once activated, enter the following interface

Choose the name of the new library and choose it yourself. I named it greenhouses.

Then select the slq window

Select the newly created database and enter the following code to execute

-- `greenhouses`
create table if not exists `greenhouses`
(
`id` int not null comment 'id',
`humidity` varchar(256) not null comment 'humidity',
`temperature` varchar(256) not null comment 'temperature',
`Soilmoisture` varchar(256) not null comment 'Soil moisture',
`CO2` varchar(256) not null comment 'co2 concentration',
`TVOC` varchar(256) not null comment 'TVOC concentration',
`illumination` varchar(256) not null comment 'illumination',
`timedata` varchar(256) not null comment 'time'
) comment ''`greenhouses`';

The meaning of the code is to create a table containing data such as temperature and humidity. You can choose the table name and comments by yourself. At this point, the slq database construction is over.

Code writing for esp8266

The code for esp8266 to write mqtt data transmission is matched with the following python code, mega2560 code and schematic diagram. It is no problem to connect directly to the pcb without the schematic diagram. I will not describe the configuration of esp8266 and the download of esp8266’s PubSubClient library. This is in It’s so easy. If you don’t know how, please refer to the article below.

Arduino IDE fool-proof offline installation of ESP8266/ESP32 firmware support package_esp8266 support package_perseverance52’s blog-CSDN blog

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// WiFi
const char *ssid = "Enter the wifi account, you can directly connect to the 5g module later without the need for a LAN"; // wifi account
const char *password = "wifi password"; // wifi password

// MQTT Broker
const char *mqtt_broker = "x1e3aa1a.ala.cn-hangzhou.emqxsl.cn"; //
const char *topic = "Greenhouses"; // The theme is determined by yourself. The subsequent theme must be the same as the python code.
const char *mqtt_username = "pythonmqtt"; // Fill in here one of the two previously authenticated accounts in emqx
const char *mqtt_password = "12345678"; // Fill in the authentication password here
const int mqtt_port = 8883; // port of MQTT over TLS/SSL

// init wifi client
WiFiClientSecure espClient;
PubSubClient client(espClient);

/*
  The common fingerprints of EMQX broker, for reference only.
  If you are not using EMQX Cloud Serverless or public EMQX broker,
  you need to calculate the sha1 fingerprint of your server certificate
  and update the 'fingerprint' variable below.
*/
// 1. fingerprint of public emqx broker. Host: broker.emqx.io
//const char* fingerprint = "B6 C6 FF 82 C6 59 09 BB D6 39 80 7F E7 BC 10 C9 19 C8 21 8E";
// 2. fingerprint of EMQX Cloud Serverless. Host: *.emqxsl.com
// const char* fingerprint = "42:AE:D8:A3:42:F1:C4:1F:CD:64:9C:D7:4B:A1:EE:5B:5E:D7:E2:B5" ;
// 3. fingerprint of EMQX Cloud Serverless. Host: *.emqxsl.cn
 const char* fingerprint = "7E:52:D3:84:48:3C:5A:9F:A4:39:9A:8B:27:01:B1:F8:C6:AD:D4:47";/ /Here is certificate authentication, which is required for private mqtt, but not required for public mqtt.


void setup() {
  Serial.begin(9600);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to the WiFi network");

  // set fingerprint
  espClient.setFingerprint(fingerprint);
  client.setServer(mqtt_broker, mqtt_port);
  client.setCallback(callback);
  while (!client.connected()) {
    String client_id = "esp8266clientrust";
    client_id + = String(WiFi.macAddress());
    Serial.printf("The client %s connects to the mqtt broker\\
", client_id.c_str());
    if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
        Serial.println("Connected to MQTT broker.");
    } else {
        Serial.print("Failed to connect to MQTT broker, rc=");
        Serial.print(client.state());
        Serial.println(" Retrying in 5 seconds.");
        delay(5000);
    }
  }

    // publish and subscribe
    //client.publish(topic, "hello emqx"); // publish message to the topic
    //client.subscribe(topic); // subscribe message from the topic
}

void callback(char* topic, byte* payload, unsigned int length) {
    Serial.print("Message arrived in topic: ");
    Serial.println(topic);
    Serial.print("Message:");
    for (int i = 0; i < length; i + + ) {
        Serial.print((char) payload[i]);
    }
    Serial.println();
    Serial.println("-----------------------");
}
void uart(){
  char c[50];
  if(Serial.available()>0){
    String uart=Serial.readString();//Whatever the serial port receives, it sends to mqtt
    //if(uart=='t'){
      //int t=Serial.parseInt();
      Serial.println(uart);
      String data=String(uart);
      char *p;
      p=strcpy(c,data.c_str());
      client.publish(topic,p,false);
  }
}
void loop() {
  /*if (!client.connected()) {
    reconnect();
  }*/
  client.loop();
  uart();
}

Python code writing

The python code is mainly used to convert mqtt to slq and send time data to slq.

You can study the method of downloading python related libraries yourself and I won’t elaborate too much here. After the esp8266 starts running, you can start the python code. You can use the Raspberry Pi as the control panel for python running code. The python code is only used as a transfer station. It doesn’t matter.

import random
from paho.mqtt import client as mqtt_client
import re
import mysql.connector
import time
# Connect to MySQL database
db = mysql.connector.connect(
    host = "Fill in the connection address of Tencent Cloud SLQ here", # Server address
    port = 22100, # port
    user = "root" , # Fill in your own user name, the default is root
    passwd = "123456" , # Password of slq database
    buffered = True,
    database="greenhouses"
)
broker = 'Fill in your own mqtt connection address'
port=8883
topic = "Greenhouses"#This is the topic, it must be the same as the esp8266 topic
client_id = f'python-mqtt-{random.randint(0, 100)}'
username = 'test'#Fill in another account for mqtt authentication here
password = '123456'#Fill in the password here
x=0
a=[]
cursor = db.cursor()
def extract_numbers(text):
    numbers = re.findall(r'\d + ', text)
    return [int(num) for num in numbers]
def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        ifrc==0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\\
", rc)
    # Set Connecting Client ID
    client = mqtt_client.Client(client_id)
    # Set CA certificate
    client.tls_set(ca_certs='D:\Agricultural Greenhouse\emqxsl-ca.crt')
    client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client
def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        print(msg.payload.decode())
        t=msg.payload.decode()
        if t:
            number = re.findall("\d + ",t) #The output result is a list
            print(number)
            timedata=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
            humidity=number[0] + ""
            temperature=number[1] + "'c"
            Soilmoisture=number[2] + "%"
            CO2=number[3] + "ppm"
            TVOC=number[4] + "mg"
            illumination=number[5] + "lx"
            sql = "INSERT INTO greenhouses (humidity,temperature,Soilmoisture,CO2,TVOC,illumination,timedata) " \
                  "VALUES (%s, %s, %s, %s, %s, %s, %s)"
            values = (humidity,temperature,Soilmoisture,CO2,TVOC,illumination,timedata)
            cursor.execute(sql, values)
            #Submit transaction
            db.commit()
            print("Soil data added successfully!")
        #numer=humidity, temperature, soil moisture, co2, tvoc, light, time
        #num=extract_numbers(msg.payload.decode())
        #print(num)
    client.subscribe(topic)
    client.on_message = on_message
def run():
    client = connect_mqtt()
    subscribe(client)
    client.loop_forever()
if __name__ == '__main__':
    run()

Various types of sensors with mega2560 development board code

It was originally intended to directly obtain data and transmit it through esp8266, but the adc reading of 8266 was not very accurate, so I chose 2560, but it can also be more cost-effective to replace it with stm32, mainly because there are many 2560s, which include the dht11 library and the sgp30 library. Download it yourself

#include "dht112.h"
#define DHT_PIN 2
#include "SGP30.h"
#define SCL 21 //You can set it yourself here
#define SDA 20 //Define SCL, SDA pin
SGP mySGP30;
u16 CO2Data,TVOCData;//Define CO2 concentration variable and TVOC concentration variable
u32 sgp30_dat;
DHT11 dht11(DHT_PIN);
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
 mySGP30.SGP30_Init();
  mySGP30.SGP30_Write(0x20,0x08);
  sgp30_dat = mySGP30.SGP30_Read();//Read the value of SGP30
  CO2Data = (sgp30_dat & 0xffff0000) >> 16;
  TVOCData = sgp30_dat & 0x0000ffff;
  while(CO2Data == 400 & amp; & amp; TVOCData == 0) //Set initial value
  {
    mySGP30.SGP30_Write(0x20,0x08);
    sgp30_dat = mySGP30.SGP30_Read();//Read the value of SGP30
    CO2Data = (sgp30_dat & amp; 0xffff0000) >> 16;//Get the CO2 concentration value
    TVOCData = sgp30_dat & amp; 0x0000ffff; //Get the TVOC value
    Serial.println("Detecting...");
    delay(500);
  }
}

void loop() {
  // put your main code here, to run repeatedly:
//--------------------------Air temperature and humidity
  int ret = dht11.read();
    if(ret == DHTLIB_ERROR_CHECKSUM) {
        Serial.println("(E) Checksum failed");
        return;
    }
    else if(ret == DHTLIB_ERROR_TIMEOUT) {
        Serial.println("(E) Read time out");
        return;
    }
//----------------------------------Soil moisture
    float P=analogRead(A0);
    float a=(1-(P-380)/643)*100;
    //Serial.print(P);
//----------------------------------Air co2 concentration
mySGP30.SGP30_Write(0x20,0x08);
  sgp30_dat = mySGP30.SGP30_Read();//Read the value of SGP30
  CO2Data = (sgp30_dat & amp; 0xffff0000) >> 16;//Get the CO2 concentration value
  TVOCData = sgp30_dat & 0x0000ffff;
//----------------------------------Light intensity
    int s=analogRead(A1);
    int b=(1024-s)/3;
    Serial.print("H");//Humidity
    Serial.print((float)dht11.getHumidity(), 2);
    Serial.print("T");//Temperature
    Serial.print((float)dht11.getTemperature(), 2);
    Serial.print("P");//Soil moisture
    Serial.print((float)a,3);
    Serial.print("C");//co2 value
    Serial.print(CO2Data,DEC);
    Serial.print("V:");//TVOC value
    Serial.print(TVOCData,DEC);
    Serial.println(b);
    //Serial.println("%");
    delay(1000);//380=100
    //1023=0
    //6.43
}

Schematic

The schematic diagram can be printed directly using Jiali Chuanghua.