from machine import Pin, Timer
from utime import sleep_ms
from umqtt.simple import MQTTClient
import network
from hcsr04 import HCSR04 # นำเข้าโมดูล Ultrasonic Sensor HC-SR04

ultra = HCSR04(trigger_pin=13,echo_pin=12) # สร้างตัวแปรแทน Ultrasonic Sensor ที่ใช้
					     # เชื่อมต่อกับ Ultrasonic Sensor โดยใช้ขา D12 และ D13

wifi_ssid = "Wokwi-GUEST"  # Fill in  your wifi info
wifi_pwd = ""

MQTT_BROKER = "mqtt.netpie.io"  
MQTT_CLIENT = "55f2409e-0eb4-4b4c-b502-f8e3bcf82dd0" # Client ID
MQTT_USER = "6Xbvq3aburaroXx92p58HWLS9aegL5VY" # Token
MQTT_PWD = "XLV8EfXnf4XQ7naKnYoSXi4vJbA6PX7R" # Secret

def update_dist(event):
    	global client
        distance = int(ultra.distance_cm()) 
        publish_str = "dist: " + str(distance) + "cm"
    	print(publish_str)
    	client.publish("@msg/dist",str(distance))
    
def wifi_connect():
    	wlan = network.WLAN(network.STA_IF)
    	wlan.active(False)
        wlan.active(True)
    	if not wlan.isconnected():
        		print('connecting to network...')
        		wlan.connect(wifi_ssid, wifi_pwd)
        		while not wlan.isconnected():
            			pass
    	print('network config:', wlan.ifconfig())
          
def init_client():
    	global client
    	print("Trying to connect to MQTT Broker.")
        try:
                client = MQTTClient(MQTT_CLIENT, MQTT_BROKER, port=1883, 		user=MQTT_USER,password=MQTT_PWD)
                client.connect()
                print("Connected to ",MQTT_BROKER)
    	except:
        		print("Trouble to init mqtt.") 

wifi_connect()  # connect to WiFi network
init_client()

dist_timer = Timer(1)
dist_timer.init(period=5000, mode=Timer.PERIODIC, callback=update_dist)

while True:
    	client.check_msg()
    	sleep_ms(1000)