Change to websocket

This commit is contained in:
2025-07-11 21:33:50 +12:00
parent f302be85c0
commit 65774837c7
2 changed files with 77 additions and 72 deletions

View File

@@ -1,53 +1,29 @@
import socket
import asyncio
import httpx
from websockets import connect
import websockets
import json
async def send_color_data(color_data, servers):
"""Send color data to all configured servers."""
tasks = [send_to_server(color_data, server) for server in servers]
await asyncio.gather(*tasks)
async def send_to_server(color_data, server):
"""Connect to a server, send color data, and close the connection."""
server_ip, server_port = server
async def send_to_server(data):
"""
Send WebSocket data to the server.
"""
try:
reader, writer = await asyncio.open_connection(server_ip, server_port)
writer.write(color_data)
await writer.drain()
writer.close()
await writer.wait_closed()
print(f"Sent data to {server_ip}:{server_port}")
except (socket.error, ConnectionError) as e:
print(f"Error sending to {server_ip}:{server_port}: {e}")
# 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}")
async def post(server, endpoint, data=""):
async with httpx.AsyncClient() as client:
r = await client.post(f"http://{server}/{endpoint}", data=data)
print(server, r)
async def main():
b = bytearray(180)
try:
ws1 = await connect("ws://10.1.1.200/external")
await asyncio.gather(post("10.1.1.200", "pattern", "external"))
while True:
print("sync")
for i in range(len(b)):
b[i] = 128
await asyncio.gather(ws1.send(b))
await asyncio.sleep(5)
finally:
await ws1.close()
await asyncio.gather(post("10.1.1.200", "pattern", "off"))
if __name__ == "__main__":
asyncio.run(main())
# Define the data to be sent
data = {
"settings": {
"color": "#00ff00"
}
}
# Server details
server = ("192.168.4.1", 80) # Example WebSocket server port
# Run the asynchronous function using asyncio.run
asyncio.run(send_to_server(data, server))