Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import appdaemon.plugins.hass.hassapi as hass
- from websocket import create_connection, WebSocketConnectionClosedException
- from PIL import Image
- from io import BytesIO
- import threading
- import time
- import paho.mqtt.client as mqtt
- class PixelItLiveView(hass.Hass):
- def initialize(self):
- self.log("PixelIt WebSocket Listener Starting...")
- # Setup MQTT with username and password
- self.mqtt_client = mqtt.Client()
- self.mqtt_client.username_pw_set("mqttuser2", password="mqttuser2")
- self.mqtt_client.connect("core-mosquitto", 1883, 60)
- self.mqtt_client.loop_start()
- # Start WebSocket listener in a new thread
- threading.Thread(target=self.listen_to_pixelit, daemon=True).start()
- def listen_to_pixelit(self):
- ws = None
- while True:
- try:
- if ws is None:
- ws = create_connection("ws://192.168.1.198:81")
- result = ws.recv()
- self.log(f"Received message: {result[:80]}...") # Log first 80 chars
- if '"liveview":"' in result:
- hex_string = result.split('"liveview":"')[1].split('"')[0]
- self.create_and_send_image(hex_string)
- except (WebSocketConnectionClosedException, ConnectionRefusedError, OSError) as e:
- self.log(f"WebSocket connection error: {e}. Reconnecting in 5 seconds...")
- time.sleep(5)
- ws = None
- except Exception as e:
- self.log(f"WebSocket error: {e}. Reconnecting in 5 seconds...")
- time.sleep(5)
- ws = None
- def create_and_send_image(self, hex_string):
- try:
- width, height = 32, 8
- img = Image.new("RGB", (width, height), "black")
- pixels = img.load()
- for i in range(0, len(hex_string), 6):
- if i + 6 <= len(hex_string):
- hex_color = hex_string[i:i+6]
- x = (i // 6) % width
- y = (i // 6) // width
- if y < height:
- r = int(hex_color[0:2], 16)
- g = int(hex_color[2:4], 16)
- b = int(hex_color[4:6], 16)
- pixels[x, y] = (r, g, b)
- # Scale up the image
- scale = 10
- resized = img.resize((img.width * scale, img.height * scale), Image.NEAREST)
- # Save locally
- image_path = "/config/www/pixelit_liveview.png"
- resized.save(image_path)
- self.log(f"Saved image to {image_path}")
- # Send raw PNG over MQTT
- buffered = BytesIO()
- resized.save(buffered, format="PNG")
- img_bytes = buffered.getvalue()
- self.mqtt_client.publish("pixelit/liveview", img_bytes, qos=1)
- self.log("Published raw PNG image to MQTT topic pixelit/liveview")
- except Exception as e:
- self.log(f"Error creating or sending image: {e}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement