Done a heap

This commit is contained in:
2025-07-12 00:55:30 +12:00
parent 65774837c7
commit c77fd30f8f
6 changed files with 841 additions and 160 deletions

View File

@@ -2,28 +2,52 @@ import asyncio
import websockets
import json
async def send_to_server(data):
"""
Send WebSocket data to the server.
"""
try:
# Connect to the WebSocket server
async with websockets.connect("ws://192.168.4.1:80/ws") as websocket:
# Serialize data to JSON and send it
await websocket.send(json.dumps(data))
except (ConnectionError, websockets.exceptions.ConnectionClosed) as e:
print(f"Error sending to {e}")
if __name__ == "__main__":
# Define the data to be sent
data = {
"settings": {
"color": "#00ff00"
}
}
class WebSocketClient:
def __init__(self, uri):
self.uri = uri
self.websocket = None
self.is_connected = False
# Server details
server = ("192.168.4.1", 80) # Example WebSocket server port
async def connect(self):
"""Establishes the WebSocket connection."""
if self.is_connected and self.websocket:
print("Already connected.")
return
# Run the asynchronous function using asyncio.run
asyncio.run(send_to_server(data, server))
try:
print(f"Connecting to {self.uri}...")
self.websocket = await websockets.connect(self.uri)
self.is_connected = True
print("WebSocket connected.")
except (ConnectionError, websockets.exceptions.ConnectionClosedOK) as e:
print(f"Error connecting: {e}")
self.is_connected = False
self.websocket = None
async def send_data(self, data):
print(data)
"""Sends data over the open WebSocket connection."""
if not self.is_connected or not self.websocket:
print("WebSocket not connected. Attempting to reconnect...")
await self.connect()
if not self.is_connected:
print("Failed to reconnect. Cannot send data.")
return
try:
await self.websocket.send(json.dumps(data))
print(f"Sent: {data}")
except (ConnectionError, websockets.exceptions.ConnectionClosed) as e:
print(f"Error sending data: {e}")
self.is_connected = False
self.websocket = None # Reset connection on error
await self.connect() # Attempt to reconnect
async def close(self):
"""Closes the WebSocket connection."""
if self.websocket and self.is_connected:
await self.websocket.close()
self.is_connected = False
self.websocket = None
print("WebSocket closed.")