· 5 months ago · Apr 30, 2025, 05:10 PM
1import appdaemon.plugins.hass.hassapi as hass
2from websocket import create_connection, WebSocketConnectionClosedException
3from PIL import Image
4from io import BytesIO
5import threading
6import time
7import paho.mqtt.client as mqtt
8
9class PixelItLiveView(hass.Hass):
10
11 def initialize(self):
12 self.log("PixelIt WebSocket Listener Starting...")
13
14 # Setup MQTT with username and password
15 self.mqtt_client = mqtt.Client()
16 self.mqtt_client.username_pw_set("mqttuser2", password="mqttuser2")
17 self.mqtt_client.connect("core-mosquitto", 1883, 60)
18 self.mqtt_client.loop_start()
19
20 # Start WebSocket listener in a new thread
21 threading.Thread(target=self.listen_to_pixelit, daemon=True).start()
22
23 def listen_to_pixelit(self):
24 ws = None
25 while True:
26 try:
27 if ws is None:
28 ws = create_connection("ws://192.168.1.198:81")
29 result = ws.recv()
30 self.log(f"Received message: {result[:80]}...") # Log first 80 chars
31
32 if '"liveview":"' in result:
33 hex_string = result.split('"liveview":"')[1].split('"')[0]
34 self.create_and_send_image(hex_string)
35
36 except (WebSocketConnectionClosedException, ConnectionRefusedError, OSError) as e:
37 self.log(f"WebSocket connection error: {e}. Reconnecting in 5 seconds...")
38 time.sleep(5)
39 ws = None
40 except Exception as e:
41 self.log(f"WebSocket error: {e}. Reconnecting in 5 seconds...")
42 time.sleep(5)
43 ws = None
44
45 def create_and_send_image(self, hex_string):
46 try:
47 width, height = 32, 8
48 img = Image.new("RGB", (width, height), "black")
49 pixels = img.load()
50
51 for i in range(0, len(hex_string), 6):
52 if i + 6 <= len(hex_string):
53 hex_color = hex_string[i:i+6]
54 x = (i // 6) % width
55 y = (i // 6) // width
56 if y < height:
57 r = int(hex_color[0:2], 16)
58 g = int(hex_color[2:4], 16)
59 b = int(hex_color[4:6], 16)
60 pixels[x, y] = (r, g, b)
61
62 # Scale up the image
63 scale = 10
64 resized = img.resize((img.width * scale, img.height * scale), Image.NEAREST)
65
66 # Save locally
67 image_path = "/config/www/pixelit_liveview.png"
68 resized.save(image_path)
69 self.log(f"Saved image to {image_path}")
70
71 # Send raw PNG over MQTT
72 buffered = BytesIO()
73 resized.save(buffered, format="PNG")
74 img_bytes = buffered.getvalue()
75
76 self.mqtt_client.publish("pixelit/liveview", img_bytes, qos=1)
77 self.log("Published raw PNG image to MQTT topic pixelit/liveview")
78
79 except Exception as e:
80 self.log(f"Error creating or sending image: {e}")
81