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

To view the data:

1. Go to http://www.hivemq.com/demos/websocket-client/
3. type "clientId-200641T" in client ID box
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "Temperature" 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
import ntptime
from machine import Pin,ADC
import ujson
from umqtt.simple import MQTTClient
from math import log

# MQTT Server Parameters
MQTT_CLIENT_ID = "200641T"
MQTT_BROKER    = "broker.mqttdashboard.com"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC     = "Temperature"

thermistor_pin=ADC(Pin(02))
sta_if = network.WLAN(network.STA_IF)
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)

def get_realtime(t):

  year,months,date,hours,minutes,seconds = t[0],t[1],t[2],t[3],t[4],t[5]
  hours+=5
  minutes+=30

  if seconds >= 60:  seconds -= 60; minutes += 1
  if minutes >= 60:  minutes -= 60; hours += 1
  if hours >= 24:  hours -= 24; date += 1
  if months == 2:
    if year%4 == 0:
      if date > 29: date -= 29; months = 3
    elif date > 28: date -= 28; months = 3
  elif (any(months == i for i in (1, 3, 5, 7, 8, 9, 10, 12))): 
    if date > 31: date -= 31; months += 1
  elif (any(months == i for i in (4, 6, 9, 11))):
    if date > 30: date -= 30; months += 1

  if months > 12: months -= 12; year += 1

  return "%02d:%02d on %04d/%02d/%02d" % (hours, minutes,year, months, date)

def send_message(temp):
  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(" Connected!")

  print("Connecting to MQTT server... ", end="")
  client.connect()
  print("Connected!")
  ntptime.settime()
  detected_time = get_realtime(time.localtime())

  message = ujson.dumps({
    "Abnormal Temperature detected ": temp, " Time ":detected_time
  })
  print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
  client.publish(MQTT_TOPIC,message)
  print("Updated")
  return 0

while True:
    sta_if.active(False)
    thermistor_value = thermistor_pin.read_u16()
    temperature=1 / (log(1 / (65535/ thermistor_value - 1)) / 3950 + 1.0 / 298.15) - 273.15
    print(temperature)
    if temperature>39:
      send_message(temperature)
     



    time.sleep(5)# For demonstration purpose