71 lines
2.1 KiB
Python
71 lines
2.1 KiB
Python
import requests
|
|
import network
|
|
import time
|
|
import machine
|
|
|
|
# Set up GPIO (ESP32 pin numbers)
|
|
PIN = 2 # Change this to your actual ESP32 pin number
|
|
|
|
# Set up Wi-Fi connection (if needed for sending HTTP requests)
|
|
ssid = 'ReCa_2G'
|
|
password = 'mosfet9843'
|
|
|
|
def send_message():
|
|
try:
|
|
|
|
# Initialize station interface
|
|
station = network.WLAN(network.STA_IF)
|
|
station.active(True)
|
|
station.config(reconnects = 5)
|
|
|
|
# Check if already connected
|
|
if not station.isconnected():
|
|
# Set mode to Station (client)
|
|
#station.mode(network.MODE_STATION)
|
|
|
|
print('Connecting to WiFi...')
|
|
station.connect(ssid, password)
|
|
|
|
# Wait for connection with a timeout
|
|
start_time = time.time()
|
|
while not station.isconnected() and (time.time() - start_time) < 10:
|
|
time.sleep(1)
|
|
|
|
if not station.isconnected():
|
|
raise Exception("Failed to connect to Wi-Fi")
|
|
|
|
# Get IP address after successful connection
|
|
ip_address = station.ifconfig()[0]
|
|
print(f"Connected to {ssid}, IP Address: {ip_address}")
|
|
|
|
# Send HTTP request
|
|
print("Sending message...")
|
|
response = requests.post(
|
|
'http://192.168.178.171:5020/send',
|
|
json={'message': 'klingel geht'},
|
|
headers={'Content-Type': 'application/json'}
|
|
)
|
|
return f"Message sent with status code {response.status_code}"
|
|
except Exception as e:
|
|
print(f"Connection failed or error while sending message: {str(e)}")
|
|
machine.reset()
|
|
return None
|
|
|
|
# Set up GPIO
|
|
pin = machine.Pin(PIN, machine.Pin.IN, machine.Pin.PULL_UP)
|
|
|
|
try:
|
|
while True:
|
|
current_state = pin.value()
|
|
if current_state == 1:
|
|
print("GPIO Pin {} is HIGH".format(PIN))
|
|
result = send_message()
|
|
print(result)
|
|
time.sleep(5)
|
|
time.sleep(0.5) # Check pin every 0,5 seconds
|
|
except KeyboardInterrupt:
|
|
print("\nProgram stopped by user")
|
|
finally:
|
|
pass # No need for GPIO cleanup in MicroPython
|
|
|