# import MicroPython modules
from umqtt.simple import MQTTClient
import machine
import network
import ujson
import time
import dht
import random
# message callback function
def callback_function(topic, msg):
print('Data transmission successful!')
print('Topic:', topic, '\nMessage:', msg)
print('\n')
# setup (i.e., void setup() in Arduino)
# initialize random number generator
random.seed(random.randint(0, 100))
# Initialize MQTT
client = MQTTClient(client_id = '649e372cfce65253e2c96e8f',
server = 'mqtt.things.ph',
port = 1883,
user = '6151c9b3061687fc9ec66686',
password = 'IwqOSc5BXlDgxNtoM9eNpEEz',
keepalive = 60,
ssl = False)
client.set_callback(callback_function)
# Try connecting to Wi-Fi Wokwi Gateway ("Wokwi-GUEST")
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!")
print('')
# define GPIO pin for DHT22 sensor
DHTsensor = dht.DHT22(machine.Pin(4))
# define GPIO pin for potentiometer
adc = machine.ADC(machine.Pin(32))
# Create JSON document object
doc = {}
# main loop (i.e., void loop() in Arduino)
while(True):
# read ADC value from potentiometer
adc_raw = adc.read()
#volts = (adc_raw / 4096) * 3.3
# get DHT measurements parameters
DHTsensor.measure()
# get temperature (degrees Celsius) and humidity (%) value
#tempC = DHTsensor.temperature()
#humid = DHTsensor.humidity()
# generate random float values for sensors
tempC = round(random.uniform(15.99, 39.99), 2)
humid = round(random.uniform(49.99, 99.99), 2)
volts = round(random.uniform(9.99, 12.99), 2)
# Define JSON dictionary Things PH payload
doc["hardware_serial"] = "Soil Nutrient"
doc["payload_fields"] = {"temperature": tempC, "humidity": humid, "battery": volts}
time.sleep(5)
# Serialized JSON content as Things PH payload
thingsph_payload = ujson.dumps(doc)
# Print values
print(thingsph_payload)
print('')
# Covert topics and payload into bytes data type
mqtt_topic = bytes('Soil Nutrient', 'utf-8')
mqtt_msg = bytes(thingsph_payload, 'utf-8')
# Connecting to Things PH IoT platform
client.connect()
# Subscribe a topic to Things PH IoT platform
client.subscribe(mqtt_topic, qos = 1)
# Publish message to Things PH IoT platform
client.publish(mqtt_topic, mqtt_msg)
# Wait a message from server (Things PH) and print the reponse using callback function
client.wait_msg()
# time delay every 30 seconds
time.sleep(30)