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

from umqtt.simple import MQTTClient

#server="backend.thinger.io"
server="bb54bc33ba884de8b311190368e138b9.s1.eu.hivemq.cloud"
ClientID = f'mqtt_test'
user = "mijimy"
#port=1883
port=8884
password = "Waw33588@"
topic = "value"
topic1 = "temp3"
TOPIC = "temp3"
temp_read=0.00

# Replace with your Wi-Fi credentials
SSID = "Wokwi-GUEST"
PASSWORD = ""

# Connect to Wi-Fi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)

# Wait for connection
while not wlan.isconnected():
    print("Connecting to Wi-Fi...")
    time.sleep(1)

print("Connected to Wi-Fi:", wlan.ifconfig())
    
def connect():
    print('Connected to MQTT Broker "%s"' % (server))
    client = MQTTClient(ClientID, server, port, 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(topicr, msgr):
    global temp_read
    print("Received:", str(msgr), "Topic:", str(topicr))
    temp_read=float(msgr)
    #print(byte_string)
    #string_value = ''.join([chr(b) for b in byte_string])
   # temp_read = float(string_value)
    print (temp_read)
    
client.set_callback(msg_received)    
client.subscribe(TOPIC)
print("Subscribed to", TOPIC)    

while 1:
  temperature=25+(random.randrange(1,50))/10
  temperature2=28+(random.randrange(1,50))/10
  temperature3=100+(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)
  msg1=str(temperature3)
  print('send message %s on topic %s' % (msg1, topic1)) 
  client.publish(topic1, msg1, qos=0)
  time.sleep(1)
  client.ping()
  client.wait_msg()
  #time.sleep(1)
  


esp:0
esp:1
esp:2
esp:3
esp:4
esp:5
esp:6
esp:7
esp:8
esp:9
esp:10
esp:18
esp:19
esp:GND.1
esp:3V3.1
esp:3V3.2
esp:GND.2
esp:RST
esp:GND.3
esp:GND.4
esp:5V.1
esp:5V.2
esp:GND.5
esp:GND.6
esp:GND.7
esp:GND.8
esp:GND.9
esp:RX
esp:TX
esp:GND.10