"""
MicroPython IoT Weather Station Example for Wokwi.com

To view the data:

1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"

Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.

Copyright (C) 2022, Uri Shaked

https://wokwi.com/arduino/projects/322577683855704658
"""

import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient

sensor_data = {'temperature': 0, 'humidity': 0}

MQTT_Client_ID = '9b1a9dfc-cb41-4403-a678-51e376eb97a3'
MQTT_Broker = 'mqtt.netpie.io'
MQTT_Token = 'u2FSQqsyE7q1ayjYnXZAvazHY5PVpvMp'
MQTT_Secret = 'LJ_VZ9NFW*DjywpIww(-RGM76P8rw66-'
# Setup Topic 
MQTT_Topic2 = '@msg/operator'

last_message = ''

led_blue = Pin(13, Pin.OUT)





# Callback function for listen incoming message
def on_message(topic,msg):
    global last_message
    incoming_message = msg.decode('utf8')
    if incoming_message == last_message:
        pass
    else :
        print('Message from {} : {}'.format(topic,incoming_message))
        if incoming_message == 'ON':
            print('LED ON')
            led_blue.value(1)
            
            
        elif incoming_message == 'OFF':
            print('LED OFF')
            led_blue.value(0)
            

d = dht.DHT22(Pin(15))

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!")

# Set Credential 
client = MQTTClient(MQTT_Client_ID, MQTT_Broker, user=MQTT_Token, password=MQTT_Secret)
client.set_callback(on_message)
# MQTT Connection Start 
client.connect()
print('Connected to {} MQTT broker'.format(MQTT_Broker))
client.subscribe(MQTT_Topic2)
print('Subcribe Topic {}'.format(MQTT_Topic2))

while True:
    client.check_msg()
    d.measure() 
    sensor_data['temperature'] = d.temperature()
    sensor_data['humidity'] = d.humidity()
    sensor_data['Name'] = "Node_1"
    publish_str = ujson.dumps({"data": sensor_data})
    print(publish_str)
    client.publish("@shadow/data/update", publish_str)
    time.sleep(2)