import network
import time
from machine import Pin, ADC, I2C
import dht
import ujson
from umqtt.simple import MQTTClient
import math
import ssd1306
# // Timer set to 3 second
timerDelay = 3
buildingProjectId = 1
# // Setting up constants for I/O pins
GROUND_PIN = 15
CONSTRUCTIONS_PIN = 19
WIFI_LED_PIN = 2
MQTT_LED_PIN = 4
POT_PIN = 34
SCREEN_WIDTH = 128 # OLED width, in pixels
SCREEN_HEIGHT = 64 # OLED height, in pixels
WIFI_SSID = "Wokwi-GUEST"
WIFI_PWD = ""
MQTT_SERVER = "test.mosquitto.org"
MQTT_PORT = 8883
MQTT_TOPIC = "constructionsMeasurings"
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(SCREEN_WIDTH, SCREEN_HEIGHT, i2c)
wifi_pin = Pin(WIFI_LED_PIN, Pin.OUT)
mqtt_pin = Pin(MQTT_LED_PIN, Pin.OUT)
ground = dht.DHT22(Pin(GROUND_PIN))
constructions = dht.DHT22(Pin(CONSTRUCTIONS_PIN))
sta_if = network.WLAN(network.STA_IF)
client = MQTTClient("device-1111", MQTT_SERVER)
status = "none";
def oledPrint(text, line):
oled.text(text, 0, 2 + line * 10)
oled.show()
def mapBetween(val, loval, hival, tolow, tohigh):
return (val - loval)/(hival-loval)*(tohigh-tolow) + tolow
def setup():
print(" Connecting to WiFi", end="")
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" \n Connected to wifi with ssid: " + WIFI_SSID)
print(" Connecting to brocker... ")
client.connect()
print(" Connected to: " + str(MQTT_SERVER))
status = "Operation";
oled.fill(0)
oledPrint("Status:" + str(status), 0);
def loop():
#//Check WiFi connection status
if sta_if.isconnected():
wifi_pin.on()
oled.fill(0)
oledPrint("Status:" + str(status), 0)
oledPrint("Sanding data... ", 1)
json = ujson.dumps({
"BuildingProjectId": buildingProjectId,
"GroundWaterLevel": ground.humidity(),
"GroundAcidityLevel": mapBetween(ground.temperature(), -40, 80, 0, 100),
"MainCostructionStates": [
{
"CompressionLevel": constructions.humidity(),
"DeformationLevel": mapBetween(constructions.temperature(), -40, 80, 0, 100),
}
]
})
try:
client.publish(MQTT_TOPIC, json)
print("###########################################")
print("Send Data:")
print(json)
print("###########################################")
mqtt_pin.on()
oledPrint("MQTT success", 2);
except:
print(" --- MQTT SENDING ERROR ---")
mqtt_pin.off()
oledPrint("MQTT error", 2);
else :
print("WiFi Disconnected")
wifi_pin.off()
oled.fill(0)
oledPrint("Status:" + str(status), 0)
time.sleep(timerDelay)
setup()
while True:
loop()
print("end");