# pub.py
import network
import socket
import time
import random

from umqtt.simple import MQTTClient
ssid = "Wokwi-GUEST"
password = ""
server="backend.thinger.io"
ClientID = f'mqtt_test'
user = "mijimy"
password = "12345678"
topic = "value"
topic1 = "temp3"
#msg = b'{"msg":"hello"}'
#TOPIC = "Properties"
#TOPIC = "mqtt_test/{{device}}/value"
TOPIC = "mqtt_test/Property/relay"

def connectw():
    #Connect to WLAN
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if wlan.isconnected() == False:
        wlan.connect(ssid, password)
    while wlan.isconnected() == False:
        print('Waiting for connection...')
        time.sleep(1)
    print(wlan.ifconfig())

try:
    connectw()
except KeyboardInterrupt:
    machine.reset()
    
def connect():
    print('Connected to MQTT Broker "%s"' % (server))
    client = MQTTClient(ClientID, server, 1883, user, password)
    client.connect()
    return client

def reconnect():
    print('Failed to connect to MQTT broker, Reconnecting...' % (server))
    time.sleep(5)
    client.reconnect()

try:
    client = connect()
except OSError as e:
    reconnect()
    
def msg_received(topic, msg):
    print("Received:", str(msg), "Topic:", str(topic))

client.set_callback(msg_received)    
client.subscribe(TOPIC)
print("Subscribed to", TOPIC)    

while True:
  temperature=25#+(random.randrange(1,50))/10
  temperature2=28#+(random.randrange(1,50))/10
  send1='"temp1":'+'"'+str(temperature)+'"'
  send2='"temp2":'+'"'+str(temperature2)+'"'
  print(send1,send2)
#  msg = b'{"temp":"send"}'
  msg=b'{'+send1+','+send2+'}'
  #msg2=b'{'+send2+'}'
 # msg=msg1+' '+msg2
  print('send message %s on topic %s' % (msg, topic))  
  client.publish(topic, msg, qos=0)
 # msg=str(temperature)
 # client.publish(topic1, msg, qos=0)
  time.sleep(1)
  #client.ping()
  client.wait_msg()
  time.sleep(1)