import time, utime, urequests, ujson
from machine import Pin
from hw import LED, RED_LED, YELLOW_LED, GREEN_LED, BUZZER
from key_pad import scan_keypad
from net import wlan
###
import uwebsockets.client
import network
import time
import ssl # Required for wss:// connections
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Error: WiFi is not connected. Please connect to WiFi externally.")
return False
print('WiFi connected, IP:', wlan.ifconfig())
return True
def websocket_echo_client():
if not connect_wifi():
return
# The uwebsockets library handles WSS (secure) automatically if SSL is available
wss_url = "wss://echo.websocket.org"
try:
# Synchronous connection using the uwebsockets client module
websocket = uwebsockets.client.connect(wss_url)
print(f"Connected to {wss_url}")
message_to_send = "Hello from MicroPython!"
websocket.send(message_to_send)
print(f"Sent: {message_to_send}")
received_message = websocket.recv()
print(f"Received: {received_message}")
if received_message == message_to_send:
print("Message echoed successfully!")
else:
print("Message mismatch or no echo.")
except Exception as e:
print(f"WebSocket error: {e}")
finally:
# Ensure the connection is closed
if 'websocket' in locals() and websocket:
websocket.close()
print("Connection closed")
# Run the client function
websocket_echo_client()
###
# ###
# import uasyncio as asyncio
# # Asynchronous function to blink the LED
# async def blink_led():
# while True:
# LED.toggle()
# await asyncio.sleep(0.5) # Pause for 0.5 seconds, allowing other tasks to run
# async def main():
# asyncio.create_task(blink_led()) # Create a task for blinking the LED
# while True:
# await asyncio.sleep(10) # Keep the main loop running indefinitely
# # Run the event loop
# try:
# asyncio.run(main())
# except KeyboardInterrupt:
# print("Program stopped.")
# ###
# protocol = "http"
# endpoint = "jsonplaceholder.typicode.com"
# response = urequests.get(f"{protocol}://{endpoint}/posts/1")
# print(ujson.loads(response.text))
# response.close()
time.sleep(0.1) # Wait for USB to become ready
print("Enter code:")
correct_code = "#1234#"
entered_code = len(correct_code) * "*"
while True:
RED_LED.on()
GREEN_LED.off()
while True:
key = scan_keypad()
if key:
YELLOW_LED.on()
print("Key pressed:", key)
entered_code = entered_code[1:] + key
print(f"Entered Code is {entered_code}")
if entered_code == correct_code:
print("Correct Code Entered!")
break
utime.sleep_ms(10) # Short delay to avoid continuous scanning
YELLOW_LED.off()
RED_LED.off()
GREEN_LED.on()
for i in range(6):
LED.on()
BUZZER.play_note("C4", 250)
LED.off()
BUZZER.play_note("G4", 250)
LED.off()