"""
MicroPython IoT Weather Station Example for Wokwi.com
This example sends temperature and humidity data from a DHT22 sensor to an Nginx proxy
using the CoAP protocol.
Ensure that your Nginx proxy is configured to handle CoAP requests.
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/322577683855704658
"""
import network
import time
import socket
import struct
from machine import Pin
import dht
# CoAP Server (Nginx proxy) details
COAP_SERVER = "192.168.1.100" # Replace with your Nginx proxy IP
COAP_PORT = 5683
COAP_PATH = b"wokwi-weather"
sensor = dht.DHT22(Pin(4))
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# Function to create a basic CoAP POST request
def build_coap_packet(temp, humidity):
# CoAP header: Version, Type, Token Length, Code, Message ID
header = b'\x40\x02' + struct.pack('!H', 12345) # Type: Confirmable, Code: POST, Message ID: 12345
token = b'\x00' # No token
options = b'\xb5' + struct.pack('!B', len(COAP_PATH)) + COAP_PATH # Uri-Path
payload_marker = b'\xff' # Payload marker
payload = f'temperature={temp}&humidity={humidity}'.encode()
return header + token + options + payload_marker + payload
# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
prev_weather = ""
while True:
print("Measuring weather conditions... ", end="")
sensor.measure()
temp = sensor.temperature()
humidity = sensor.humidity()
# Build CoAP packet
coap_packet = build_coap_packet(temp, humidity)
# Send packet to the CoAP server
sock.sendto(coap_packet, (COAP_SERVER, COAP_PORT))
print(f"Sent data to CoAP server: temperature={temp}, humidity={humidity}")
time.sleep(10)