WU_HuiQiao
Published © GPL3+

Remote environment monitoring system.

Allowing 24/7 monitoring of environment with instant notifications from two directions, easily deployment!

IntermediateFull instructions provided1,476
Remote environment monitoring system.

Things used in this project

Hardware components

DHT22 Temperature and Humidity Sensor
DFRobot DHT22 Temperature and Humidity Sensor
to collect the real time of temperature and humidity
×1
Buzzer
Buzzer
to send alert
×1
Adafruit Feather HUZZAH with ESP8266 WiFi
Adafruit Feather HUZZAH with ESP8266 WiFi
×1
ESP8266 ESP-12E
Espressif ESP8266 ESP-12E
×1
Arduino Proto Shield
Arduino Proto Shield
×1

Software apps and online services

Arduino IDE
Arduino IDE
Visual Studio 2015
Microsoft Visual Studio 2015

Hand tools and fabrication machines

Soldering iron (generic)
Soldering iron (generic)
Soldering Tool Stand, for use with W100PG Irons
Soldering Tool Stand, for use with W100PG Irons
PCB, For DMB-4775
PCB, For DMB-4775

Story

Read more

Schematics

schematic for the realtime detector

Code

node1.ino

C/C++
code for node ( 2 nodes in total )
/*********By HuiQiao
*********/

#include <ESP8266WiFi.h>

#include <DHT.h>

#define DHTPIN D5   

#define Vibrating_PIN D1 

#define LED_PIN 12

#define DHTTYPE DHT22   // DHT 22  

DHT dht(DHTPIN, DHTTYPE);


const char *ssid = "your WiFi ";
const char *password = "WiFi password";
const IPAddress serverIP(); //,IP address of your server 
uint16_t serverPort = 8098;         
WiFiClient client; 


int PIN_Sta;


void setup()
{
    Serial.begin(115200);
    Serial.println();
    dht.begin();
   pinMode(Vibrating_PIN, INPUT);
   pinMode(LED_PIN, OUTPUT);
    WiFi.mode(WIFI_STA);
//    WiFi.setSleep
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.println("Connected");
    Serial.print("IP Address:");
    Serial.println(WiFi.localIP());
}

int GetCnt=0;
char SendBuf[50]={0};
char tempBuf[10]={0};
char humiBuf[10]={0};
int SendTimer=0;

void Getdata_WifiSend(void)
{
      
  float humi = dht.readHumidity(); 
  float temp = dht.readTemperature();  
  if (isnan(humi) || isnan(temp)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  dtostrf(temp,2,2,tempBuf);
  dtostrf(humi,2,2,humiBuf); 
  Serial.print("Humidity: ");  
  Serial.print(humi);
  Serial.println("%  Temperature: "); 
  Serial.print(temp);
  Serial.println("C "); 

}

int Deifg = 0;

void loop()
{  

    Serial.println("");
    if (client.connect(serverIP, serverPort)) 
    {
        Serial.println("");
      //  client.print("Hello world!");                    
        while (client.connected() || client.available()) 
        {
           if(GetCnt++>3000)//3S Get 
           {
                Getdata_WifiSend();
                GetCnt=0;
               
               
            }
            if(++SendTimer>1000)//500ms Send
            {
               SendTimer=0;
               sprintf(SendBuf,"ID11,Temperature:%s,Humidity:%s,Vibration:%d\r\n",tempBuf,humiBuf,PIN_Sta);
                client.write(SendBuf); 
            }
             PIN_Sta=digitalRead(Vibrating_PIN);
            if (client.available()) 
            {
                String line = client.readStringUntil('\n'); 
                if(line.indexOf("Set_ID1")!=-1)
                {
                     if(line.indexOf("ON")!=-1)
                     {
                      digitalWrite(LED_PIN, HIGH);   
                      }
                       else if(line.indexOf("OFF")!=-1)
                     {
                        digitalWrite(LED_PIN,LOW);   
                      }
                  }
            }
            delay(1);
        }
        Serial.println("");
        client.stop(); 
    }
    else
    {
        Serial.println("");
        client.stop(); 
    }

}

node2.ino

C/C++
code for node 2
/*********BY HuiQiao*********/

#include <ESP8266WiFi.h>
#include <DHT.h>

#define DHTPIN 14     // NodeMCU D4

#define Vibrating_PIN 5 //   NodeMCU D1

#define DHTTYPE DHT22   // DHT 22  

DHT dht(DHTPIN, DHTTYPE);

const char *ssid = "";
const char *password = "";
const IPAddress serverIP(); 
uint16_t serverPort = 8098;         
WiFiClient client; 


int PIN_Sta;


void setup()
{
    Serial.begin(115200);
    Serial.println();
    dht.begin();
   pinMode(Vibrating_PIN, INPUT);
   pinMode(LED_PIN, OUTPUT);
     digitalWrite(LED_PIN,HIGH);   
    WiFi.mode(WIFI_STA);
//    WiFi.setSleep
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.println("Connected");
    Serial.print("IP Address:");
    Serial.println(WiFi.localIP());
}

int GetCnt=0;
char SendBuf[50]={0};
char tempBuf[10]={0};
char humiBuf[10]={0};
int SendTimer=0;

void Getdata_WifiSend(void)
{
      
  float humi = dht.readHumidity(); 
  float temp = dht.readTemperature();  
  
  if (isnan(humi) || isnan(temp)) {
   Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }
  //temp=25.3;
  //humi=55.9;
  dtostrf(temp,2,2,tempBuf);
  dtostrf(humi,2,2,humiBuf);
  Serial.print("Humidity: ");  
  Serial.print(humi);
  Serial.println("%  Temperature: "); 
  Serial.print(temp);
  Serial.println("C "); 

}

int Deifg = 0;

void loop()
{  

    Serial.println("");
    if (client.connect(serverIP, serverPort)) 
    {
        Serial.println("");
       // client.print
        while (client.connected() || client.available()) 
        {
           if(GetCnt++>3000)//3S Get 
           {
                Getdata_WifiSend();
                GetCnt=0;
               
               
            }
            if(++SendTimer>1000)//1000ms Send
            {
               SendTimer=0;
               
               sprintf(SendBuf,"ID22,Temperature:%s,Humidity:%s,Vibration:%d\r\n",tempBuf,humiBuf,PIN_Sta);
                client.write(SendBuf); 
            }
             PIN_Sta=digitalRead(Vibrating_PIN);
            if (client.available()) 
            {
                String line = client.readStringUntil('\n'); 
                if(line.indexOf("Set_ID2")!=-1)
                {
                     if(line.indexOf("ON")!=-1)
                     {
                      digitalWrite(LED_PIN, HIGH);   
                      }
                       else if(line.indexOf("OFF")!=-1)
                     {
                        digitalWrite(LED_PIN,LOW);   
                      }
                  }
            }
            delay(1);
        }
        Serial.println("");
        client.stop(); 
    }
    else
    {
        Serial.println("");
        client.stop(); 
    }

}

Form1.cs

C/C++
code for the host PC ( windows APP )
/*******By HuiQiao*********/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace TCPClient
{
    public partial class Form1 : Form
    {
        private TcpClient myTcpClient = null;// TcpClient

        Thread ConnectThread;

        string ipAddress;//ip
        int Port = 0;
        private bool Conctifg = false;
        bool LianJSta = false;

        private NetworkStream networkstrem = null;
        private Thread ReceiveThread;
        public Form1()
        {
            InitializeComponent();
        }
        public class APIs
        {
            [DllImport("Kernel32.dll")]
            public static extern bool Beep(int frequency, int duration);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //getIPAddress();//.IP,
        }
        
        public static string Substring(string text, string start, string end)
        {

            Regex rg = new Regex("(?<=(" + start + "))[.\\s\\S]*?(?=(" + end + "))", RegexOptions.Multiline | RegexOptions.Singleline);
            string NameText = rg.Match(text).Value;
            return NameText;
        }


        bool ifg = false;
        private void ConnectMethod()
        {
            myTcpClient = new TcpClient();                      //myTcpClient
            try
            {
                myTcpClient.Connect(ipAddress, Port);

                networkstrem = myTcpClient.GetStream();

                ReceiveThread = new Thread(ReceiveDataMethod);
                ReceiveThread.Start();
 
                
                Invoke((new Action(() => 
                {
                    button1.Text = "Disconnect";
                    LianJSta = true;
                })));
            }
            catch (Exception)
            {
                
                Invoke((new Action(() =>
                {
                    button1.Text = "Connect";
                })));
                try { ReceiveThread.Abort(); }
                catch { }
                try { networkstrem.Dispose(); }
                catch { }
                try { myTcpClient.Close(); }//TCP
                catch { }
            }
        }
        public static string StringMidStrEx(string sourse, string startstr, string endstr)
        {
            string result = string.Empty;
            int startindex, endindex;
            try
            {
                startindex = sourse.IndexOf(startstr);
                if (startindex == -1)
                    return result;
                string tmpstr = sourse.Substring(startindex + startstr.Length);
                endindex = tmpstr.IndexOf(endstr);
                if (endindex == -1)
                    return result;
                result = tmpstr.Remove(endindex);
            }
            catch (Exception ex)
            {
                Console.WriteLine("MidStrEx Err:" + ex.Message);
            }
            return result;
        }


        private void ReceiveDataMethod()
        {
            int RecvCnt = 0;
            byte[] recvBytes = new byte[1024*1024];
            while (true)
            {
                if (Conctifg)//  
                {
                    break;
                }
                try
                {
                    //
                    if ((myTcpClient.Client.Poll(20, SelectMode.SelectRead)) && (myTcpClient.Client.Available == 0))
                    {
                        myTcpClient.Close();
                    }

                    RecvCnt = networkstrem.Read(recvBytes, 0, recvBytes.Length);

                    Invoke((new Action(() =>
                    {
                        
                        string RxStr = new ASCIIEncoding().GetString(recvBytes, 0, RecvCnt);
                        if (RxStr.IndexOf("Temperature") != -1 && RxStr.IndexOf("\r\n") != -1)
                        {
                            string tempStr; string humiStr; string VibStr; string Kqsd; string Gz;
                            tempStr = StringMidStrEx(RxStr, "Temperature:", ",");
                            humiStr = StringMidStrEx(RxStr, "Humidity:", ",");
                            VibStr = StringMidStrEx(RxStr, "Vibration:", "\r\n");
                            if (tempStr != "" && humiStr != "" && VibStr != "" )
                            {
                                float Tempnum = float.Parse(tempStr);
                                float HumiNum=float.Parse(humiStr);
                                Text1.Text = tempStr;
                                Text2.Text = humiStr;
                                Text3.Text = VibStr;
                                if (Tempnum < 29|| HumiNum<40|| HumiNum>70)
                                {
                                    ifg = true;
                                }
                                else
                                {
                                    ifg = false;

                                }
                            }

                        }


                    })));
                }
                catch (Exception ex)//
                {
                    //
                    try
                    {
                        Invoke((new Action(() =>
                        {
                            button1.Text = "Connect";
                        })));
                    }
                    catch
                    {

                    } 
                    
                    try {
                        ReceiveThread.Abort();
                        break;//break  
                    }
                    catch {

                    }
                    try {
                        networkstrem.Dispose();

                    }
                    catch { }
                    try {

                        myTcpClient.Close();

                    }//TCP
                    catch { }
                }
            }
        }



        
        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "Connect")
            {
                ipAddress = comboBox1.Text.ToString();//IP
                Port = Convert.ToInt32(textBox1.Text.ToString());

                ConnectThread = new Thread(ConnectMethod);
                ConnectThread.Start();
                Conctifg = false;
                timer1.Start();
            }
            else
            {
                try {
                    Conctifg = true;
                    ReceiveThread.Abort(); 
                    networkstrem.Dispose();
                    myTcpClient.Close();//tcp
                    timer1.Stop();
                } catch {

                } 
                Invoke((new Action(() =>
                {
                    button1.Text = "Connect";
                })));
                LianJSta = false;
            }
        }

        private void comboBox1_DropDown(object sender, EventArgs e)
        {
           // getIPAddress();//ip
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            try {
                ReceiveThread.Abort();

            }
            catch { }
            try { networkstrem.Dispose(); }
            catch { }
            try { myTcpClient.Close(); }//TCP
            catch { }

            System.Environment.Exit(0);
        }

        private static byte[] strToToHexByte(String hexString)
        {
            int i;
            bool Flag = false;
            hexString = hexString.Replace(" ", "");//
            if ((hexString.Length % 2) != 0)
            {
                Flag = true;
            }
            if (Flag == true)
            {
                byte[] returnBytes = new byte[(hexString.Length + 1) / 2];

                try
                {
                    for (i = 0; i < (hexString.Length - 1) / 2; i++)
                    {
                        returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                    }
                    returnBytes[returnBytes.Length - 1] = Convert.ToByte(hexString.Substring(hexString.Length - 1, 1).PadLeft(2, '0'), 16);

                }
                catch
                {
                    for (i = 0; i < returnBytes.Length; i++)
                    {
                        returnBytes[i] = 0;
                    }
                    MessageBox.Show("16A-F,0", "");
                }
                return returnBytes;
            }
            else
            {
                byte[] returnBytes = new byte[(hexString.Length) / 2];
                try
                {
                    for (i = 0; i < returnBytes.Length; i++)
                    {
                        returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                    }
                }
                catch
                {
                    for (i = 0; i < returnBytes.Length; i++)
                    {
                        returnBytes[i] = 0;
                    }
                    MessageBox.Show("16A-F,0", "");
                }
                return returnBytes;
            }
        }

        string ste = "";
        int count = 0;
        bool flag = false;
        private void timer1_Tick_1(object sender, EventArgs e)
        {
          

                if (ifg == true)
                {

                    if (flag == false)
                    {
                        APIs.Beep(2000, 500);
                        flag = true;
                    }
                    else
                    {
                        if (count++ > 50)
                        {
                            count = 0;
                            APIs.Beep(2000, 500);
                        }
                    }

                }
           
        }
        
    }
}

Credits

WU_HuiQiao
1 project • 8 followers
I like building things.
Contact

Comments

Please log in or sign up to comment.