# import dht
# import network
# import machine
# import time
# from umqtt.simple import MQTTClient

# # Wifi and MQTT broker details
# WIFI_SSID = 'Wokwi-GUEST'
# WIFI_PASSWORD = ''
# MQTT_BROKER = 'broker.mqttdashboard.com'
# MQTT_CLIENT_ID = 'poultry'
# MQTT_TOPIC_TEMPERATURE = 'home/temperature'
# MQTT_TOPIC_HUMIDITY = 'home/humidity'
# MQTT_TOPIC_MOVEMENT = 'home/movement'

# # Initialize the DHT22 sensor on pin 18
# dht22 = dht.DHT22(machine.Pin(18))
# # Initialize the PIR sensor on pin 19
# pir_pin = machine.Pin(19, machine.Pin.IN)

# # Initialize the buzzer pin (e.g., GPIO 21) with PWM
# buzzer_pin = machine.Pin(21, machine.Pin.OUT)
# pwm = machine.PWM(buzzer_pin, freq=1, duty=0)  # Initialize PWM with frequency 0 and duty cycle 0

# # Wi-Fi connection
# def connect_wifi(ssid, password):
#     wlan = network.WLAN(network.STA_IF)
#     wlan.active(True)
#     if not wlan.isconnected():
#         print('Connecting to network...') # display the connection wifi on wokwi
#         wlan.connect(ssid, password)
#         while not wlan.isconnected():
#             pass
#     print('Network connected!') # confirmation of network connected

# # MQTT connection
# def connect_mqtt():
#     client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
#     client.connect()
#     print('MQTT connected!')
#     return client

# # Set the frequency and duration for buzzer
# def play_tone(frequency, duration):
#     pwm.freq(frequency)   # Set the frequency
#     pwm.duty(512)         # Set the duty cycle to 50% (range is 0-1023)
#     time.sleep(duration)  # Play the tone for the specified duration
#     pwm.duty(0)           # Stop the tone

# motion_detected = False
# motion_start_time = 0

# # this trigger_action function being called if PIR sensor detected motion for 5 seconds
# def trigger_action():
#     print("Motion detected for 5 seconds. Triggering action!")
#     play_tone(500, 1)

# # Connect the WiFi and MQTT Broker first
# connect_wifi(WIFI_SSID, WIFI_PASSWORD)
# connect_mqtt()

# while True:
#     try:
#         # Create a varible for MQTT
#         client = connect_mqtt()

#         # Trigger a new measurement from the DHT22 sensor
#         dht22.measure()
#         # Get temperature and humidity from the DHT22 sensor
#         temp = dht22.temperature()
#         humidity = dht22.humidity()
        
#         # Print temperature and humidity values
#         print('Temperature: %3.1f C' % temp)
#         print('Humidity: %3.1f %%' % humidity)

#         # Send the temperature and Humidity data to MQTT Broker
#         client.publish(MQTT_TOPIC_TEMPERATURE, str(temp).encode())
#         client.publish(MQTT_TOPIC_HUMIDITY, str(humidity).encode())
        
#         # Check the PIR sensor for motion
#         if pir_pin.value():
#             if not motion_detected:
#                 motion_detected = True
#                 motion_start_time = time.ticks_ms()  # Record the start time
#             else:
#                 elapsed_time = time.ticks_diff(time.ticks_ms(), motion_start_time)
#                 if elapsed_time >= 5000:  # Check if 5 seconds have passed
#                     trigger_action() # being called if PIR sensor detect motion for 5 seconds
#                     # Reset the motion detection status
#                     motion_detected = False
#                     motion_start_time = 0
#             print("Motion: Movement Detected")
#             client.publish(MQTT_TOPIC_MOVEMENT, "Motion: Movement Detected") # this is for audio
#         else:
#             motion_detected = False
#             motion_start_time = 0
#             print("Motion: No Movement")
#             client.publish(MQTT_TOPIC_MOVEMENT, "") #this is for audio
        
#         # Wait 2 seconds before the next measurement
#         time.sleep(2)
#     except OSError as e:
#         # Print an error message if reading the sensor fails
#         print('Failed to read sensor:', e)




import dht
import network
import machine
import time
from umqtt.simple import MQTTClient

# Wifi and MQTT broker details
WIFI_SSID = 'Wokwi-GUEST'
WIFI_PASSWORD = ''
MQTT_BROKER = 'broker.mqttdashboard.com'
MQTT_CLIENT_ID = 'poultry'
MQTT_TOPIC_TEMPERATURE = 'home/temperature'
MQTT_TOPIC_HUMIDITY = 'home/humidity'
MQTT_TOPIC_MOVEMENT = 'home/movement'

# Initialize the DHT22 sensor on pin 18
dht22 = dht.DHT22(machine.Pin(18))
# Initialize the PIR sensor on pin 19
pir_pin = machine.Pin(19, machine.Pin.IN)

# Initialize the buzzer pin (e.g., GPIO 21) with PWM
buzzer_pin = machine.Pin(21, machine.Pin.OUT)
pwm = machine.PWM(buzzer_pin, freq=1, duty=0)  # Initialize PWM with frequency 0 and duty cycle 0

# Wi-Fi connection
def connect_wifi(ssid, password):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('Connecting to network...') # display the connection wifi on wokwi
        wlan.connect(ssid, password)
        while not wlan.isconnected():
            pass
    print('Network connected!') # confirmation of network connected

# MQTT connection
def connect_mqtt():
    client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
    client.connect()
    print('MQTT connected!')
    return client

# Set the frequency and duration for buzzer
def play_tone(frequency, duration):
    pwm.freq(frequency)   # Set the frequency
    pwm.duty(512)         # Set the duty cycle to 50% (range is 0-1023)
    time.sleep(duration)  # Play the tone for the specified duration
    pwm.duty(0)           # Stop the tone

motion_detected = False
motion_start_time = 0

# this trigger_action function being called if PIR sensor detected motion for 5 seconds
def trigger_action():
    print("Motion detected for 5 seconds. Triggering action!")
    play_tone(500, 1)

# Connect the WiFi and MQTT Broker first
connect_wifi(WIFI_SSID, WIFI_PASSWORD)
connect_mqtt()

while True:
    try:
        # Create a varible for MQTT
        client = connect_mqtt()

        # Trigger a new measurement from the DHT22 sensor
        dht22.measure()
        # Get temperature and humidity from the DHT22 sensor
        temp = dht22.temperature()
        humidity = dht22.humidity()
        
        # Print temperature and humidity values
        print('Temperature: %3.1f C' % temp)
        print('Humidity: %3.1f %%' % humidity)

        # Send the temperature and Humidity data to MQTT Broker
        client.publish(MQTT_TOPIC_TEMPERATURE, str(temp).encode())
        client.publish(MQTT_TOPIC_HUMIDITY, str(humidity).encode())
        
        # Check the PIR sensor for motion
        if pir_pin.value():
            if not motion_detected:
                motion_detected = True
                motion_start_time = time.ticks_ms()  # Record the start time
            else:
                elapsed_time = time.ticks_diff(time.ticks_ms(), motion_start_time)
                if elapsed_time >= 5000:  # Check if 5 seconds have passed
                    trigger_action() # being called if PIR sensor detect motion for 5 seconds
                    # Reset the motion detection status
                    motion_detected = False
                    motion_start_time = 0
            print("Motion: Movement Detected")
            client.publish(MQTT_TOPIC_MOVEMENT, "Motion: Movement Detected") # this is for audio
        else:
            motion_detected = False
            motion_start_time = 0
            print("Motion: No Movement")
            client.publish(MQTT_TOPIC_MOVEMENT, "") #this is for audio
        
        # Wait 2 seconds before the next measurement
        time.sleep(2)
    except OSError as e:
        # Print an error message if reading the sensor fails
        print('Failed to read sensor:', e)

$abcdeabcde151015202530fghijfghij