import time
import machine
import time
import utime
from umqtt.simple import MQTTClient
import micropython
import esp
import uasyncio
import gc
import ubinascii
import ntptime
gc.collect()
esp.osdebug(None)
pub_client_id = 'FamClaes006_%s' % ubinascii.hexlify(machine.unique_id()).decode()
topic_pub_temp = b'esp/ds18b20/temperature'
pub_mqtt_server = 'mqttpub.fam-claes.be'
pub_mqtt_port = 8444
topic_pub_ts = b"CLSensors/timestamp/#"
pub_mqtt_server = 'test.mosquitto.org'
pub_mqtt_port = 1883
last_ping = time.time()
ping_interval = 60
def sub_cb(topic,msg):
    print((topic,msg))
    
def connect_mqtt():
  global pub_client_id, pub_mqtt_server, pub_mqtt_port
  pub_client = MQTTClient(pub_client_id, pub_mqtt_server, port=pub_mqtt_port,keepalive=60 )
  pub_client.set_callback(sub_cb)
  pub_client.connect()
  pub_client.subscribe(topic_pub_ts)
  print('Connected to public %s MQTT broker' % (pub_mqtt_server))
  return pub_client
def restart_and_reconnect():
  print('Failed to connect to MQTT broker. Reconnecting...')
  utime.sleep_ms(15)
  machine.reset()
  
def reset():
    print("Resetting...")
    time.sleep(5)
    machine.reset()
    
async def run():
    print("Local time before synchronization:%s" %str(time.localtime()))
    ntptime.settime()
    print("Local time after synchronization:%s" %str(time.localtime()))
    try:
      pub_client = connect_mqtt()
      last_message = time.time()
    except OSError as e:
      restart_and_reconnect()
    print('Start monitoring...')
    while True:
        if False:
            # Blocking wait for message
            pub_client.wait_msg()
        else:
            # Non-blocking wait for message
            pub_client.check_msg()
            # Then need to sleep to avoid 100% CPU usage (in a real
            # app other useful actions would be performed instead)
            global last_ping
            if (time.time() - last_ping) >= ping_interval:
                pub_client.ping()
                last_ping = time.time()
                now = time.localtime()
                print(f"Pinging MQTT Broker, last ping :: {now[0]}/{now[1]}/{now[2]} {now[3]}:{now[4]}:{now[5]}")
            time.sleep(1)
    print("Disconnecting...")
    pub_client.disconnect()
if __name__ == '__main__':
  try:
    uasyncio.run(run())
  except:
    print ("Encountered error...rebooting")
    restart_and_reconnect()