import network
import requests
from time import sleep
from machine import Pin
from hcsr04 import HCSR04
sensor = HCSR04(trigger_pin=5, echo_pin=16, echo_timeout_us=10000)

# Wi-Fi credentials
ssid = 'SSID'
password = 'PASSWORD'

# Phone number in international format
phone_number = 'PHONE_NUMBER'
# Callmebot API key
api_key = 'API_KEY'

def init_wifi(ssid, password):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(ssid, password)
    connection_timeout = 50  # Increased timeout
    while connection_timeout > 0:
        if wlan.status() >= 3:
            break
        connection_timeout -= 1
        print('Waiting for Wi-Fi connection...')
        sleep(1)
    
    if wlan.status() == 3:
        print('Wi-Fi connection failed with status:', wlan.status())
        return False
    else:
        print('Connection successful!')
        network_info = wlan.ifconfig()
        print('IP address:', network_info[0])
        return True

def send_message(phone_number, api_key, message):
    url = f'https://api.callmebot.com/whatsapp.php?phone={phone_number}&text={message}&apikey={api_key}'
    try:
        response = requests.get(url)
        if response.status_code == 200:
            print('Message sent successfully!')
        else:
            print('Error sending message:', response.status_code, response.text)
    except Exception as e:
        print('Request error:', e)

try: 
    if init_wifi(ssid, password):
        while True:
            distance = sensor.distance_cm()
            if (distance > 20) and (distance < 120):
                message = 'Pohyb%20zaznamenan'
                send_message(phone_number, api_key, message)
                sleep(0.5)
except Exception as e:
    print('An unexpected error occurred:', e)