Browse Source

Advertise status to HA when it comes online

master
Nathaniel Walizer 2 years ago
parent
commit
c43ae65df3
3 changed files with 43 additions and 50 deletions
  1. +1
    -27
      blinky.json
  2. +34
    -23
      blinky.py
  3. +8
    -0
      gradients.py

+ 1
- 27
blinky.json View File

@@ -1,27 +1 @@
{
"length": 50,
"patterns": [
{
"length": 50,
"gradient": {
"preset": "peacock"
},
"cycle_length": 20
}, {
"length": 0,
"gradient": {
"colors": [
"red",
"orange",
"yellow",
"green",
"blue",
"purple",
"black"
]
},
"cycle_length": 7,
"march": true
}
]
}
{"length": 50, "power_on": true, "patterns": [{"gradient": {"preset": "pumpkin"}, "cycle_length": 20}]}

+ 34
- 23
blinky.py View File

@@ -37,6 +37,7 @@ class Device:
state_topic = f"light/{id}/state"
command_topic = f"light/{id}/cmd"
fx_state_topic = f"light/{id}/fx"
ha_topic = 'homeassistant/status'

ready = False
changed = False
@@ -45,33 +46,40 @@ class Device:
power_on = True
effect = None

def advertise_locked(client, device):
client.publish(
f"homeassistant/light/{device.id}/config",
json.dumps({
'unique_id': device.id,
'device': {
'name': "blinky",
'identifiers': [device.id],
},

'state_topic': device.state_topic,
'command_topic': device.command_topic,
'effect_state_topic': device.fx_state_topic,

'schema': "json",

'effect': True,
'effect_list': device.effects,
})
)

device.publish_state_locked()

def on_mqtt_connect(client, device, flags, rc):
if rc == 0:
with device.lock:
print("Connected to MQTT")
client.publish(
f"homeassistant/light/{device.id}/config",
json.dumps({
'unique_id': device.id,
'device': {
'name': "blinky",
'identifiers': [device.id],
},

'state_topic': device.state_topic,
'command_topic': device.command_topic,
'effect_state_topic': device.fx_state_topic,

'schema': "json",

'effect': True,
'effect_list': device.effects,
})
)
client.subscribe(device.command_topic)

device.ready = True
if device.should_publish:
device.publish_state_locked()
Device.advertise_locked(client, device)

client.subscribe(device.command_topic)
client.subscribe(device.ha_topic)

device.cond.notify_all()
else:
print(f"MQTT connection failed: {rc}")
@@ -92,6 +100,9 @@ class Device:
def on_mqtt_message(client, device, msg):
if msg.topic == device.command_topic:
device.set_mqtt_config(json.loads(msg.payload))
elif msg.topic == device.ha_topic:
with device.lock:
Device.advertise_locked(client, device)

def __init__(self, effects=[]):
print(f"Creating device with ID {self.id}")
@@ -268,4 +279,4 @@ with device.lock:
#while not file_changed and not device.is_changed():
# device.cond.wait(sleeptime)

device.lock.acquire()
device.lock.acquire()

+ 8
- 0
gradients.py View File

@@ -92,6 +92,14 @@ class Gradients:
Colors.black
])

beads = Gradient([
Colors.purple,
Colors.black,
Colors.green,
Colors.yellow,
Colors.black
])

irish = Gradient([
Colors.dark_green,
Colors.black,


Loading…
Cancel
Save