This article is a client/server programming example for a wireless network weather station (Client/Server Programming for Weather Stations via Wireless Networking) using two esp32 microcontrollers communicate over a wireless network. By setting the DHT22 and LDR sensor installed as a server working in AP mode and another esp32 microcontroller board working as a client and media via a custom port to read the temperature, humidity and digital values ​​obtained from the LDR sensor as shown in Figure 1.

(Figure. 1 Our board)

Equipment

In the article, the following microcontroller boards and sensors are used.

  1. 2 ESP32
  2. DHT22
  3. LDR

The connection between the esp32 microcontroller and the sensor is shown in Figure 2.

(Figure. 2 Connection between ESP32 and sensor)

From Figure 2, it can be seen that the connections are as follows.

ESP32DHT22LDR
GPIO39I/O
GPIO15I/O
3V3VccVcc
GNDGNDGND

Example Code

The example program consists of 2 parts: the part of the board connected to the sensor module. By setting it to work as an AP and a service machine. Communications on port 3002 and client programs for requesting temperature, humidity, and readings from the LDR sensor.

Server

#############################################################
# WeatherStationS.py
# For server
# (C) 2021, JarutEx
#############################################################
from machine import Pin,I2C,ADC
import dht
import machine
import gc
import time
import os
import sys
import machine as mc
import network as nw
import ubinascii as ua
import socket
import ssd1306
#############################################################
# system
gc.enable()
gc.collect()
machine.freq(240000000)

i2c = I2C(0,scl=Pin(4), sda=Pin(5), freq=100000)
display = ssd1306.SSD1306_I2C(128, 32, i2c)

###########################################################
# Sensor
dht22 = dht.DHT22(Pin(15))
ldr = ADC(Pin(39))
ldr.width( ADC.WIDTH_12BIT ) # 12bit
ldr.atten( ADC.ATTN_11DB ) # 3.3V

###########################################################
# Main program
APif = nw.WLAN(nw.AP_IF)
# Set WiFi access point name (formally known as ESSID) and WiFi channel
APif.config(essid='JarutEx_WS',
            password='123456789',
            authmode=nw.AUTH_WPA2_PSK,
            channel=1, hidden=True)
APif.active(True)

def showInfo():
    # shiw IPAddress
    display.fill(0)
    display.text("--AP Config.--",0,0,1)
    display.text("{}".format(APif.ifconfig()[0]), 0, 8, 1)
    display.text("{}".format(APif.config('essid')), 0, 16, 1)
    display.show()

showInfo()
# main loop
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP
s.bind(('',3002))
s.listen(5)
try:
    while True:
        conn, addr = s.accept()
        request = conn.recv(1024)
        if (request == b'tem'):
            dht22.measure()
            conn.send("{}".format(dht22.temperature()))
        elif (request == b'hum'):
            dht22.measure()
            conn.send("{}".format(dht22.humidity()))
        elif (request == b'ldr'):
            conn.send("{}".format(ldr.read()))
        else:
            conn.send("na")
        conn.close()
except KeyboardInterrupt:
    pass
s.close()
# end of program
APif.active(False)

Client

An example of a client-side program that connects to the AP of the service provider and request tem, hum and ldr data to port 3002 respectively and get the result is shown in Figure 3.

#############################################################
# WeatherStationC.py
# For client
# (C) 2021, JarutEx
#############################################################
import machine
import gc
import time
import os
import sys
import network as nw
import ubinascii as ua
import socket

#############################################################
# system
gc.enable()
gc.collect()
machine.freq(240000000)

###########################################################
# Main program
sta = nw.WLAN( nw.STA_IF )
sta.active(True)
# Connect
sta.connect('JarutEx_WS','123456789')
while not sta.isconnected():
    time.sleep_ms(200)
print(sta.ifconfig())
serverInfo = socket.getaddrinfo( '192.168.4.1', 3002, 0, socket.SOCK_STREAM )[0]
print("Server info : {}".format(serverInfo))
# req temp
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
s.connect(serverInfo[-1])
s.write(b'tem')
result = s.readline()
s.close()
print("Temperature : {}C".format(result))
# req humid
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
s.connect(serverInfo[-1])
s.write(b'hum')
result = s.readline()
s.close()
print("Humidity : {}%".format(result))
#req LDR
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
s.connect(serverInfo[-1])
s.write(b'ldr')
result = s.readline()
print("LDR Value : {}".format(result))
s.close()


###########################################################
# End of Program
sta.active(False)
(Figure. 3 Result from client side)

Conclusion

From this example, you will find that it is an application from the previously mentioned WiFi article. By adding about having one board act as an AP and a temperature, humidity and value of the LDR provider and clients are linked to the same AP, so both nodes are under the same network. After that, the client requests data to the port. On the server, when a request is received, it checks the type of request and takes action on that request, and returns the results of its work.

If you understand the principles of programming Client/Server of this article will be able to apply them in many network commands. And finally, have fun with programming.

If you want to talk with us, feel free to leave comments below!!

References

  1. xxx, ESP32 Networking
  2. micropython.org : Network basics
  3. micropython.org : network — network configuration
  4. micropython.org : Network – TCP Sockets
  5. micropython.org : socket — socket module

(C) 2021, By Jarut Busarathid and Danai Jedsadathitikul
Updated 2021-12-07