Usage examples¶
Simple switch¶
A simple single switch example. It prints the state of the switch on change.
Import modules¶
First import all the necessary modules:
1from nirahmq import *
2from nirahmq.components import Switch
Declare the switch callback¶
The switch command callback is called each time a payload is sent from
Home Assistant to the switch. The expected payloads are
Switch.payload_on for activating
and Switch.payload_off for
deactivating the switch.
5def callback(switch: Switch, payload: str) -> None:
6 match payload:
7 case switch.payload_on:
8 switch.set_state(True)
9 print("TURNING ON")
10 case switch.payload_off:
11 switch.set_state(False)
12 print("TURNING OFF")
13 case _:
14 print(f"Invalid payload `{payload}`!")
Note
Notice that the switch component is sending its new state back to Home Assistant.
Is Switch.optimistic was
set to True manually or by not defining
Switch.state_topic,
this would not be required.
Declare the discovery info¶
Declare a bare bones device with a single switch component.
17discovery_info = DiscoveryInfo(
18 device=DeviceInfo(identifiers="nirahmq-device"),
19 origin=OriginInfo(name="Python example"),
20 components={
21 'switch': Switch(
22 command_topic="~/command",
23 state_topic="~/state",
24 command_callback=callback
25 )
26 }
27)
Main program¶
The preferred way to use the Device and
MQTTClient classes is inside a context manager.
29with (MQTTClient("homeassistant.lan", username="<username>", password="<password>") as client,
30 Device(client, discovery_info) as device):
31 input("Press enter to exit")
Full code sample¶
Full code sample
1from nirahmq import *
2from nirahmq.components import Switch
3
4
5def callback(switch: Switch, payload: str) -> None:
6 match payload:
7 case switch.payload_on:
8 switch.set_state(True)
9 print("TURNING ON")
10 case switch.payload_off:
11 switch.set_state(False)
12 print("TURNING OFF")
13 case _:
14 print(f"Invalid payload `{payload}`!")
15
16
17discovery_info = DiscoveryInfo(
18 device=DeviceInfo(identifiers="nirahmq-device"),
19 origin=OriginInfo(name="Python example"),
20 components={
21 'switch': Switch(
22 command_topic="~/command",
23 state_topic="~/state",
24 command_callback=callback
25 )
26 }
27)
28
29with (MQTTClient("homeassistant.lan", username="<username>", password="<password>") as client,
30 Device(client, discovery_info) as device):
31 input("Press enter to exit")
Temperature light¶
A single light with color temperature support in Kelvin.
Import modules¶
First import all the necessary modules:
1import json
2
3from nirahmq import *
4from nirahmq.components import Light
5from nirahmq.enums import LightColorMode
Declare the light callback¶
The light command callback is called each time a payload is sent from Home Assistant to the light. The expected payloads are JSON encoded.
Important
Currently only the JSON schema is supported with the Light component.
8def callback(light: Light, payload: str) -> None:
9 try:
10 cmd = json.loads(payload)
11 if cmd['state'] == 'ON':
12 if not callback.prev_state:
13 print("Turning light ON")
14
15 if brightness := cmd.get('brightness'):
16 print(f"Setting brightness to {brightness / 2.55:.0f}%")
17
18 if temp := cmd.get('color_temp'):
19 print(f"Setting color temperature to {temp}K")
20
21 callback.prev_state = True
22 elif cmd['state'] == 'OFF':
23 print("Turning light OFF")
24
25 callback.prev_state = False
26 except json.decoder.JSONDecodeError:
27 pass
28
29
30callback.prev_state = False # Function static variable
Note
Here, the light is working in optimistic mode, as no
Light.state_topic is defined.
Declare the discovery info¶
Declare a bare bones device with a single light component.
32discovery_info = DiscoveryInfo(
33 device=DeviceInfo(identifiers="nirahmq-device"),
34 origin=OriginInfo(name="Python example"),
35 components={
36 'light': Light(
37 command_topic="~/command",
38 supported_color_modes=[LightColorMode.COLOR_TEMP],
39 color_temp_kelvin=True,
40 command_callback=callback
41 )
42 }
43)
Main program¶
45with (MQTTClient("homeassistant.lan", username="<username>", password="<password>") as client,
46 Device(client, discovery_info) as device):
47 input("Press enter to exit")
Full code sample¶
Full code sample
1import json
2
3from nirahmq import *
4from nirahmq.components import Light
5from nirahmq.enums import LightColorMode
6
7
8def callback(light: Light, payload: str) -> None:
9 try:
10 cmd = json.loads(payload)
11 if cmd['state'] == 'ON':
12 if not callback.prev_state:
13 print("Turning light ON")
14
15 if brightness := cmd.get('brightness'):
16 print(f"Setting brightness to {brightness / 2.55:.0f}%")
17
18 if temp := cmd.get('color_temp'):
19 print(f"Setting color temperature to {temp}K")
20
21 callback.prev_state = True
22 elif cmd['state'] == 'OFF':
23 print("Turning light OFF")
24
25 callback.prev_state = False
26 except json.decoder.JSONDecodeError:
27 pass
28
29
30callback.prev_state = False # Function static variable
31
32discovery_info = DiscoveryInfo(
33 device=DeviceInfo(identifiers="nirahmq-device"),
34 origin=OriginInfo(name="Python example"),
35 components={
36 'light': Light(
37 command_topic="~/command",
38 supported_color_modes=[LightColorMode.COLOR_TEMP],
39 color_temp_kelvin=True,
40 command_callback=callback
41 )
42 }
43)
44
45with (MQTTClient("homeassistant.lan", username="<username>", password="<password>") as client,
46 Device(client, discovery_info) as device):
47 input("Press enter to exit")
Multi-sensor device¶
A device containing multiple sensor components.
Import modules¶
First import all the necessary modules:
1import random
2
3from nirahmq import *
4from nirahmq.components import Sensor
5from nirahmq.enums import SensorClass
Declare the discovery info¶
Declare a bare bones device with one temperature and one humidity sensor.
7discovery_info = DiscoveryInfo(
8 device=DeviceInfo(name="Multi device", identifiers="nirahmq-device"),
9 origin=OriginInfo(name="Python example"),
10 components={
11 'temp': Sensor(
12 device_class=SensorClass.TEMPERATURE,
13 suggested_display_precision=1,
14 state_topic="~/state"
15 ),
16 'humid': Sensor(
17 device_class=SensorClass.HUMIDITY,
18 suggested_display_precision=1,
19 state_topic="~/state"
20 )
21 }
22)
Main program¶
Inside the context, the values for the temperature and humidity sensor is set to random values.
24with (MQTTClient("homeassistant.lan", username="<username>", password="<password>") as client,
25 Device(client, discovery_info) as device):
26 device['temp'].set_value(random.uniform(20, 30))
27 device['humid'].set_value(random.uniform(40, 60))
28
29 input("Press enter to exit")
Full code sample¶
Full code sample
1import random
2
3from nirahmq import *
4from nirahmq.components import Sensor
5from nirahmq.enums import SensorClass
6
7discovery_info = DiscoveryInfo(
8 device=DeviceInfo(name="Multi device", identifiers="nirahmq-device"),
9 origin=OriginInfo(name="Python example"),
10 components={
11 'temp': Sensor(
12 device_class=SensorClass.TEMPERATURE,
13 suggested_display_precision=1,
14 state_topic="~/state"
15 ),
16 'humid': Sensor(
17 device_class=SensorClass.HUMIDITY,
18 suggested_display_precision=1,
19 state_topic="~/state"
20 )
21 }
22)
23
24with (MQTTClient("homeassistant.lan", username="<username>", password="<password>") as client,
25 Device(client, discovery_info) as device):
26 device['temp'].set_value(random.uniform(20, 30))
27 device['humid'].set_value(random.uniform(40, 60))
28
29 input("Press enter to exit")