HomeWizard is a company located in the Netherlands that designs and produces devices for the smart homes.
One of their very popular products is the so-called P1 meter which you can connect to the P1 port of your digital meter. Once connected and installed, you can follow your electricity production (in case you have solar panels) and consumption.
You can then register on the HomeWizard website and view your power consumption (and gas if that's relevant) on a dedicated web page you get for free.
Note that this website only saves your data for one year. After that one year, your history is deleted and everything starts overnew.
Unless you subscribe for €12/year, then they will save your data "forever" and you will also have extra functionality available through their app.
Next to the P1 meter, they have lots of other useful devices, one of them being the energy socket which can be controlled by the HomeWizard app (subscription necessary).
HomeWizard also has a REST API which can be used by everyone and which allows you to control the devices (e.g. the energy socket) yourself using your own preferred application.
Later in this chapter, I'll give an example of a Python application that controls an energy socket using MQTT. Very interesting, keep on reading!
As soon as they (Fluvius) switched my meter from analogue (ouch... I loved that one...) to digital (duh!!! didn't want this, really...) I purchased myself a P1 meter from HomeWizard. I'm by no means neither affiliated nor supported by HomeWizard, but their P1 meter is the best there is on the market. And it's cheap too: only €24.95!
Installing it is not that difficult. You connect the P1 meter to the digital meter (the ring of the P1 meter starts to blink white, since not connected yet), press 2 seconds on the center knob until the ring starts to blink blue.
Then install the HomeWizard app on your smartphone, find the device and start the connection (using WiFi) of your P1 meter to your router.
See here for a detailed installation overview.
Once the paring is done, the P1 meter ring becomes steady green.
That's all there is!
If you register on the HomeWizard website, you will also get a special URL (https://www.hwenergy.app) where you can see your power consumption in real time, day, week, month or year scale.
You can see it on a browser on your PC or in the HomeWizard app on your smartphone (be it less clear since smaller screen real estate...)
The real time view is, well, impressive!
If you have other devices from HomeWizard, you can add them too to the web view.
As said in the introduction, if you subscribe for the Energy+ subscription, you can do and see a lot more with their website and app.
Every HomeWizard device must be assigned an IP address. To know the IP address, there are several methods available.
One of the methods I wanted to use, is the dns-sd protocol as described in the discovery page on the HomeWizard API website.
This is what they have:
$ dns-sd -B _hwenergy._tcp .
Browsing for _hwenergy._tcp
DATE: ---Tue 29 Oct 2024---
14:51:03.565 ...STARTING...
Timestamp A/R Flags if Domain Service Type Instance Name
14:51:03.566 Add 3 7 local. _hwenergy._tcp. energysocket-AABBCC
14:51:03.566 Add 3 7 local. _hwenergy._tcp. energysocket-DDEEFF
14:51:03.566 Add 3 7 local. _hwenergy._tcp. energysocket-001122
14:51:03.566 Add 3 7 local. _hwenergy._tcp. p1meter-334455
14:51:03.566 Add 3 7 local. _hwenergy._tcp. kwhmeter-667788
14:51:03.566 Add 3 7 local. _hwenergy._tcp. watermeter-ABCDEF
However, dns-sd is apparently not by default installed on the Trixie image of the Raspberry Pi. Whatever I tried to install it (I even compiled the source code for it), I was not able to get dns-sd up and running.
I gave up, since there's an alternative that can be use and that is installed on the Raspberry Pi: avahi-browse. avahi-browse is part of avahi-daemon that should be installed by default on the Trixie distribution. If not: sudo apt install avahi-daemon and you're good to go.
Using this utility, you can scan for all services on the network or you can filter out (or in, depending on how you look at it) certain services.
For HomeWizard v1, the service is _hwenergy._tcp
For HomeWizard v2, the service is _homewizard._tcp
Since I'm using v1, I have to use the service _hwenergy._tcp.
I don't know all the options for dns-sd, but for avahi-browse the following important options are available (there's more, add --help to see all of them):
-a: browse for all service types. You should not use option -a if you also provide a service. You will get an error message.
-r: resolve the services automatically
-p: display output in parsable format (JSON-alike)
-t: terminate the application immediately after the information has been retrieved (otherwise, avahi-browse remains active in the background and keeps on looking for matching services)
A few examples:
avahi-browse -pt _hwenergy._tcp:
pi@trixie2:~ $ avahi-browse -pt _hwenergy._tcp
+;eth0;IPv6;p1meter-35AEDE;_hwenergy._tcp;local
+;eth0;IPv4;p1meter-35AEDE;_hwenergy._tcp;local
+;eth0;IPv4;energysocket-36B516;_hwenergy._tcp;local
+;eth0;IPv4;energysocket-37F3FC;_hwenergy._tcp;local
If I would not add the -t, then avahi-browse would "hang" and not come back to the command line.|
This overview shows a simple overview of the detected devices, not showing yet the IP address of the individual devices.
You see the ethernet iface, the IP protocol (IP4 and/or IP6), the complete device name (including a unique code, I guess)
pi@trixie2:~ $ avahi-browse -rt _hwenergy._tcp
+ eth0 IPv6 p1meter-35AEDE _hwenergy._tcp local
+ eth0 IPv4 p1meter-35AEDE _hwenergy._tcp local
+ eth0 IPv4 energysocket-36B516 _hwenergy._tcp local
+ eth0 IPv4 energysocket-37F3FC _hwenergy._tcp local
= eth0 IPv4 energysocket-36B516 _hwenergy._tcp local
hostname = [energysocket-36B516.local]
address = [192.168.1.63]
port = [80]
txt = ["api_enabled=1" "path=/api/v1" "product_name=Energy Socket" "product_type=HWE-SKT" "serial=5c2faf36b516"]
= eth0 IPv6 p1meter-35AEDE _hwenergy._tcp local
hostname = [p1meter-35AEDE.local]
address = [192.168.1.60]
port = [80]
txt = ["api_enabled=1" "path=/api/v1" "product_name=P1 Meter" "product_type=HWE-P1" "serial=5c2faf35aede"]
= eth0 IPv4 p1meter-35AEDE _hwenergy._tcp local
hostname = [p1meter-35AEDE.local]
address = [192.168.1.60]
port = [80]
txt = ["api_enabled=1" "path=/api/v1" "product_name=P1 Meter" "product_type=HWE-P1" "serial=5c2faf35aede"]
= eth0 IPv4 energysocket-37F3FC _hwenergy._tcp local
hostname = [energysocket-37F3FC.local]
address = [192.168.1.62]
port = [80]
txt = ["api_enabled=1" "path=/api/v1" "product_name=Energy Socket" "product_type=HWE-SKT" "serial=5c2faf37f3fc"]
As you can see here, there's much more detail for each and every device.
Every line starting with a + sign is the same as the one shown with the previous command
Every line starting with a = sign shows a lot of detailed information about the device, amont others, the IP address!
And that's what we were looking for.
You can combine options like so:
pi@trixie2:~ $ avahi-browse -rpt _hwenergy._tcp
+;eth0;IPv6;p1meter-35AEDE;_hwenergy._tcp;local
+;eth0;IPv4;p1meter-35AEDE;_hwenergy._tcp;local
+;eth0;IPv4;energysocket-36B516;_hwenergy._tcp;local
+;eth0;IPv4;energysocket-37F3FC;_hwenergy._tcp;local
=;eth0;IPv6;p1meter-35AEDE;_hwenergy._tcp;local;p1meter-35AEDE.local;192.168.1.60;80;"api_enabled=1" "path=/api/v1" "product_name=P1 Meter" "product_type=HWE-P1" "serial=5c2faf35aede"
=;eth0;IPv4;p1meter-35AEDE;_hwenergy._tcp;local;p1meter-35AEDE.local;192.168.1.60;80;"api_enabled=1" "path=/api/v1" "product_name=P1 Meter" "product_type=HWE-P1" "serial=5c2faf35aede"
=;eth0;IPv4;energysocket-36B516;_hwenergy._tcp;local;energysocket-36B516.local;192.168.1.63;80;"api_enabled=1" "path=/api/v1" "product_name=Energy Socket" "product_type=HWE-SKT" "serial=5c2faf36b516"
=;eth0;IPv4;energysocket-37F3FC;_hwenergy._tcp;local;energysocket-37F3FC.local;192.168.1.62;80;"api_enabled=1" "path=/api/v1" "product_name=Energy Socket" "product_type=HWE-SKT" "serial=5c2faf37f3fc"
This information is shown in a less "chaotic" way. The parameter -p requested to show the information in a parsable format, which has happened.
And to show you that you shoud not use the option -a in combination with a service, see the output of the following command:
pi@trixie2:~ $ avahi-browse -arpt _hwenergy._tcp
Too many arguments
If I leave out the service, so running avahi-browse -arpt, then I get a whole bunch of information rolling over my screen. Too much to show here...
HomeWizard allows you to approach their devices through a REST API. See Local API documentation to start with it.
One important thing: they call it local API since you can only access it through your internal network (maybe wise to do so for security reasons, to start with).
Another thing is that you have to allow each and every device to communicate with that local REST API. Normally, when you add a device through the HomeWizard app on your smartphone, the local API is by default activated. But you can switch it off, if you like.
To add a device, open the HomeWizard app on your smartphone. Pass your credentials if asked.
Next, press the cog wheel located in the upper right corner of the screen. This will open a side bar with lots if items. The important item now is Devices. Click on it, it will show all devices that are turned on.
One of the devices should be the P1 meter, since you just installed it.
Select the P1 meter; you will see lots of information:
Incoming power
Outgoing power
Voltages on the different lines (one voltage for 1-phase nets, 3 voltages for 3-phase nets)
And at the end you will see an item called Local API and a switch which is ON by default. This allows you to control the device using the local REST API.
Next to the switch you will also see the IP address that has been assigned to this device by the DHCP of your main router.
If you would have other devices, e.g. an energy socket, then this device would also show up in the list of devices. If you select that device, you will see other parameters, but at the end you should also see an item called Local API with a switch. And the IP address assigned to that device when you added it.
I also bought 2 energy sockets when I bought my P1 meter. To add those devices to my list of devices, I had to do the following:
Put the energy sockets in a mains outlet
Press the switch at the top to switch on the device (as long as the device is not switched on, you won't see it in the list of devices in the app)
In the app, section Devices, click the Add Device button
Select the device, in my case the energy socket
Follow the guidelines on the screen:
Make sure the socket is powered and press Next
Press the button on the energy socket until the light starts blinking blue: the device is in the pairing mode now
Once the blinking blue is visible, press next on the app: device setup is ongoing
Once the detection is done, it will ask you to which WiFi network it should connect. If there was already a previous connection with a WiFi access point, it will propose that one but you can always select another WiFi AP.
Pass the credentials, you can save them if you prefere for a next connection, the credentials will then not be asked anymore.
Next question is what this device will do: lots of predefined tasks, but there's also Other. This allows you to create an own item.
If Other was selected, create a new item with your preferred name.
Next, the app asks you if it should lock the device or not. Advice: do not lock the device.
After that, the new device will be in the list of devices. You can select the new device to see its parameters and also the Local API switch position.
For an energy socket device, the following parameters are available/visible:
Power import
Power export
Total power in and out
Voltage level
You will also see + Add task. If you press the button, you will see 4 items on the next screen, 3 of them for which you have to have an Energy+ subscription. Only the Timer task is freely available.
Other features available are the brightness of the status light and if you want to lock the device or not. But remember, the advice is not to lock the device since that will lock the energy socket in the ON state and you won't be able to switch it off again with the switch on the device.
To know what is possible you have to read the API Documentation on the HomeWizard website.
There are currently 2 versions of the API: v1 and v2.
v2 is in a 'moving state', that is: the API's are gradually moving away from v1 and will in the end be addressing v2 (at least, that's my perception)
v2 is also more secure (supports https) and feature-rich.
I will use v1 for the moment, since on the introduction page it's mentioned that some things are still "planned" for v2 (and available in v1, at least for my devices P1 meter and energy sockets).
To access the devices through the REST API, it's important to know the IP address assigned to the devices, since the protocol is like so:
When using curl:
curl http://<IP_ADDRESS>/api[/.....]
Based upon the API call, you can get different kinds of information from the device. For details, see this web page.
The following curl command has to be used to read out the data of the P1 meter in JSON format:
curl http://<IP ADDRESS>/api/v1/data
The result is the following (pretty-printed using a NPP plug-in):
{
"active_current_a": 12.53,
"active_current_l1_a": 2.73,
"active_current_l2_a": 9.38,
"active_current_l3_a": 0.42,
"active_power_average_w": 0,
"active_power_l1_w": -615,
"active_power_l2_w": -2218,
"active_power_l3_w": 75,
"active_power_w": -2759,
"active_tariff": 2,
"active_voltage_l1_v": 233.7,
"active_voltage_l2_v": 236.3,
"active_voltage_l3_v": 231.8,
"external": [
],
"meter_model": "Fluvius 253967035_D",
"montly_power_peak_timestamp": 260610173000,
"montly_power_peak_w": 1660,
"smr_version": 50,
"total_power_export_kwh": 2714.599,
"total_power_export_t1_kwh": 1996.611,
"total_power_export_t2_kwh": 717.988,
"total_power_import_kwh": 1471.288,
"total_power_import_t1_kwh": 678.652,
"total_power_import_t2_kwh": 792.636,
"unique_id": "3153414733323030323438313337",
"wifi_ssid": "ProxiVaren",
"wifi_strength": 100
}
What you see above is close to what you will get when you read out the P1 meter telegram (see below). The only difference is that the OBIS code is replaced with "understandable text" and the values are represented in a different way.
Also, other items will be shown here. Some of them are:
WiFi strength
WiFi SSID
And vice versa: the P1 meter telegram will show other items not present in here. But many of the items will return in the real telegram.
Reading out the state of the P1 meter is not possible. It's not described in the REST API for the P1 meter. See this page where you will see at the top that state is not supported for the P1 meter.
Still trying to do so will return you this:
$ curl http://192.168.1.60/api/v1/state
Nothing matches the given URI
This, to show you that not all REST API's are valid for all HomeWizard devices. Hence, the importance of reading very well the REST API documentation.
One that deserves special mentioning is reading out the telegram from the P1 meter using curl:
curl http://<IP ADDRESS>/api/v1/telegram
The result is (in my case):
$ curl http://192.168.1.60/api/v1/telegram
/FLU5\253967035_D
0-0:96.1.4(50221)
1-0:94.32.1(400)
0-0:96.1.1(3153414733323030323438313337)
0-0:96.1.2()
0-0:1.0.0(260620113651S)
1-0:1.8.1(000678.652*kWh)
1-0:1.8.2(000792.636*kWh)
1-0:2.8.1(001996.611*kWh)
1-0:2.8.2(000716.496*kWh)
0-0:96.14.0(0002)
1-0:1.4.0(00.000*kW)
1-0:1.6.0(260610173000S)(01.660*kW)
0-0:98.1.0(13)(1-0:1.6.0)(1-0:1.6.0)(250601000000S)(250511083000S)(02.017*kW)(250701000000S)(250614131500S)(01.683*kW)(250801000000S)(250731141500S)(01.879*kW)(250901000000S)(250829134500S)(02.193*kW)(251001000000S)(250920130000S)(01.990*kW)(251101000000W)(251019091500S)(02.373*kW)(251201000000W)(251122173000W)(02.409*kW)(260101000000W)(251205174500W)(02.341*kW)(260201000000W)(260116191500W)(02.520*kW)(260301000000W) 260224203000W)(02.427*kW)(260401000000S)(260307174500W)(02.223*kW)(260501000000S)(260403101500S)(01.966*kW)(260601000000S)(260515101500S)(02.033*kW)
1-0:1.7.0(00.000*kW)
1-0:2.7.0(02.445*kW)
1-0:21.7.0(00.000*kW)
1-0:41.7.0(00.000*kW)
1-0:61.7.0(00.049*kW)
1-0:22.7.0(00.411*kW)
1-0:42.7.0(02.083*kW)
1-0:62.7.0(00.000*kW)
1-0:32.7.0(232.9*V)
1-0:52.7.0(236.4*V)
1-0:72.7.0(231.6*V)
1-0:31.7.0(001.90*A)
1-0:51.7.0(008.83*A)
1-0:71.7.0(000.37*A)
0-0:96.3.10(1)
0-0:17.0.0(99.999*kW)
1-0:31.4.0(999.99*A)
0-1:96.3.10(0)
0-2:96.3.10(0)
0-3:96.3.10(0)
0-4:96.3.10(0)
0-0:96.13.0()
!FBDC
This is of course a snapshot, since a telegram is sent out every second. The above command is taking a snapshot of the actual telegram.
Anyway, you can see what it all reveals. You have the OBIS code and the value belonging to that OBIS code.
This section describes in great detail what each and every line in a P1 telegram means.
Below is a resume of the most important parts of the P1 telegram.
1-0:32.7.0(232.9*V): actual voltage on phase L1
1-0:52.7.0(236.4*V): actual voltage on phase L2
1-0:72.7.0(231.6*V): actual voltage on phase L3
See orange colour above
Same is valid for the current going through the different wires L1, L2 and L3. See the blue colour above.
Another one that is very important for the Flemish part of Belgium is the capacity tariff (capaciteitstarief).
This value is calculated every 15 minutes: it takes the average current used during that time. The value is compared to previous and future values calculated the same way. At the end of the month, the highest value is stored on the servers of - in my case - Fluvius and the value is reset to 0 again, ready for the calculation for the next month.
This is the definition given by Fluvius about the capacity tariff (Dutch, English translation later):
Wat is een piekvermogen (formule volgens Fluvius: https://www.fluvius.be/nl/veelgestelde-vragen/mijn-fluvius/verbruik#piekvermogen)
Het maandelijks piekvermogen voor elektriciteit is de hoogste piek of de grootste afname van het elektriciteitsnet op één kwartier binnen die maand. Die piek zal hoog zijn als je veel toestellen op hetzelfde moment gebruikt of apparaten in huis hebt die veel energie in een korte tijdspanne verbruiken.
Je huishoudtoestellen zelf vermelden vaak ook hun piekvermogen in kilowatt (kW) of watt (W). Let op dat je dit piekvermogen op een hele korte tijdspanne niet verwart met het piekvermogen dat je ziet in Mijn Fluvius. De waarden op Mijn Fluvius zijn namelijk gemiddelde waarden over een heel kwartier.
Momenteel toont Mijn Fluvius bij digitale meters enkel het piekvermogen van de afname, en dus niet van de injectie. Klanten met een AMR-meter in plaats van een gewone digitale meter zien zowel het piekvermogen van afname als injectie, voor elektriciteit én voor gas.
Benieuwd hoe je energieleverancier piekvermogens gebruikt om je factuur op te maken? De VREG, de Vlaamse Regulator van de Elektriciteits- en Gasmarkt, legt het voor je uit in dit filmpje. Je vindt ook een uitleg op Mijn Fluvius. Klik daarvoor in het menu op “Netkosten - Capaciteitstarief”.
At the end of the year, all those values are again averaged over 12 months and that value is used to calculate the extra cost: the capacity tariff.
The capacity tariff is represented by the OBIS code 1.6.0, shown in red in the output above.
The lower you can keep the peak value, the cheaper your electricity bill will be. Unfortunately (and typicallly Belgium), the more you take care of the environment, the less you get rewarded. Why? Whatever you do to keep the value as low as possible, they will always take a value of 2.5kW as a minimum value.
If you look to the example above, our current peak value is 1.66kW but still, they will take 2.5kW as capacity tariff.
I understand the reasoning for the capacity tariff. Through this way they want to make the consumer aware they should not switch on too many electrical devices in one go to avoid overload of the whole electricity net. The providers want to spread the load more equally over the net to avoid having to adapt the network each and everywhere to address the hunger for electricity.
But it's a pity they don't reward people doing even more effort to reduce the peak power consumption. Greedy wolves...
Another part of the P1 telegram contains the peak demand value of the last x months. For a detailed explanation about this section in the telegram, see Last 13 peak demands.
_________________________________________________________________________________________________________________________________________________
Note that the P1 meter does not have a state endpoint in the REST API.
I can use the same curl command to read out the state, data and device information for an energy socket (this one does have a state command).
State information:
curl http://<IP_ADDRESS>/api/v1/state
Example result:
$ curl http://192.168.1.62/api/v1/state
{"power_on":true,"switch_lock":false,"brightness":38}
Here we can see the socket is switched on, the brightness of the LED ring is set to 38 (min. 0, max. 255) and the switch lock is set to false.
Data information:
curl http://<IP_ADDRESS>/api/v1/data
Example result:
$ curl http://192.168.1.62/api/v1/data
{
"active_apparent_power_va": 0.0,
"active_current_a": 0.0,
"active_frequency_hz": 50.02,
"active_power_factor": 1.0,
"active_power_l1_w": 0.0,
"active_power_w": 0.0,
"active_reactive_power_var": 0.0,
"active_voltage_v": 233.625,
"total_power_export_kwh": 0.0,
"total_power_export_t1_kwh": 0.0,
"total_power_import_kwh": 0.0,
"total_power_import_t1_kwh": 0.0,
"wifi_ssid": "SisyPhus",
"wifi_strength": 100
}
Here we see totally different information. Even the frequency is read out! See blue text.
This way, if there were a consumer connected to the socket, we could see how much current it draws, the power on L1, total power consumed (or pushed back, should you connect a HomeWizard battery to this socket) and so on...
Device information
curl http://<IP_ADDRESS>/api
Example result:
$ curl http://192.168.1.62/api
{"product_name":"Energy Socket","product_type":"HWE-SKT","serial":"5c2faf37f3fc","firmware_version":"4.09","api_version":"v1"}
This way, you can filter out a lot of data from the devices, using the REST API in combination with curl.
Note that there's more than state, device, telegram and data API's. There's also an identity, a system and an error API available.
Again, for more info, look at the HomeWizard API documentation website and figure out what can be done with all of those API's
Next to using curl to read out and control HomeWizard devices, you can also use a higher level language, since curl is a bit cumbersome to use.
What I have tried, is the following:
Using a Python script to address the HomeWizard devices
Using MQTT to broadcast and receive topics to control and read out devices
For MQTT, I have an MQTT broker (mosquitto) running on one of my Raspberry Pi's. From my Python script, I'm publishing MQTT messages to that broker based on what I want to address or do.
I'm then using Putty, connected to the Raspberry Pi, to use mosquitto_pub to publish, for example, commands to the energy socket.
As seen in the previous section, I can read out a lot of information from the energy socket using curl: state, data and device (and even more, see this page).
There's a few packages that are used in the minimalist Python application. Install if not present.
import requests
import paho.mqtt.client as mqtt
import time
Below is a completely functional, be it minimal, Python application.
What does it do?
Using the IP address of the device you want to access
Prepare a dedicated API (state, in this example)
Defining the MQTT broker address and port
Defining topic names for the different parameters of the command state
Creating an MQTT client
Defining a set and get method to retrieve or set the 3 possible states of an energy socket: power state, lock state and brightness
Defining an MQTT callback method to process incoming MQTT messages
Create an infinite loop to keep the app running
You then have to use the command mosquitto_pub from another terminal to access the correct topic with the correct parameter. More on that later.
Python code
Below is the full Python code I've used to read out and control one of my energy sockets. Works like a charm!
import requests
import paho.mqtt.client as mqtt
import time
# Homewizard Energy Socket IP
HW_IP = "192.168.x.x" # Replace with your socket's IP
HW_API_URL = f"http://{HW_IP}/api/v1/state"
# MQTT Broker settings
MQTT_BROKER = "192.168.x.x" # or your MQTT broker IP
MQTT_PORT = 1883
MQTT_TOPIC_STATE = "homewizard/energy_socket/state"
MQTT_TOPIC_POWER = "homewizard/energy_socket/power"
MQTT_TOPIC_COMMAND = "homewizard/energy_socket/command"
MQTT_TOPIC_LOCK = "homewizard/energy_socket/switch_lock"
MQTT_TOPIC_BRIGHTNESS = "homewizard/energy_socket/brightness"
# Initialize MQTT client
mqtt_client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
mqtt_client.connect(MQTT_BROKER, MQTT_PORT)
# Fetch socket state from Homewizard API
def get_socket_state():
try:
response = requests.get(HW_API_URL)
response.raise_for_status()
data = response.json()
return data.get("power_on", False), data.get("power", 0.0)
except Exception as e:
print(f"Error fetching socket state: {e}")
return None, None
# Set socket state via Homewizard API
def set_socket_state(power_on=None, switch_lock=None, brightness=None):
payload = {}
if power_on is not None:
payload["power_on"] = power_on
if switch_lock is not None:
payload["switch_lock"] = switch_lock
if brightness is not None:
payload["brightness"] = brightness
try:
response = requests.put(HW_API_URL, json=payload)
response.raise_for_status()
return True
except Exception as e:
print(f"Error setting socket state: {e}")
return False
# MQTT callback for commands
def on_message(client, userdata, msg):
if msg.topic == MQTT_TOPIC_COMMAND:
command = msg.payload.decode().upper()
if command == "ON":
set_socket_state(power_on=True)
elif command == "OFF":
set_socket_state(power_on=False)
elif msg.topic == MQTT_TOPIC_LOCK:
lock_state = msg.payload.decode().upper() == "LOCK"
set_socket_state(switch_lock=lock_state)
elif msg.topic == MQTT_TOPIC_BRIGHTNESS:
try:
brightness = int(msg.payload.decode())
set_socket_state(brightness=brightness)
except ValueError:
print("Invalid brightness value. Must be an integer between 0 and 255.")
# Set up MQTT client
mqtt_client.on_message = on_message
mqtt_client.subscribe(MQTT_TOPIC_COMMAND)
mqtt_client.subscribe(MQTT_TOPIC_LOCK)
mqtt_client.subscribe(MQTT_TOPIC_BRIGHTNESS)
mqtt_client.loop_start()
# Main loop: Publish state periodically
try:
while True:
power_on, power = get_socket_state()
if power_on is not None:
mqtt_client.publish(MQTT_TOPIC_STATE, "ON" if power_on else "OFF")
mqtt_client.publish(MQTT_TOPIC_POWER, str(power))
time.sleep(1) # Update every second
except KeyboardInterrupt:
mqtt_client.loop_stop()
mqtt_client.disconnect()
Once you have this running, you can execute the following command to change the state of the switch (ON or OFF):
mosquitto_pub -h localhost -t "homewizard/energy_socket/command" -m "ON" (or -m "OFF")
Same for the brightness, only the topic is different and of course the value (between 0 and 255):
mosquitto_pub -h localhost -t "homewizard/energy_socket/brightness" -m "150"
This should change the brightness of the green LED ring on the energy socket.
Next to the REST API, there's also a GitHub repo called python-homewizard-energy and created by the HomeWizard crew to be used in HomeAutomation. But this library can also be used in an async application.
Repo can be found here: https://github.com/homewizard/python-homewizard-energy.
I've also created a small application based on the info I found on the above website. I diverted from their application because it's missing guards (e.g. they ask unconditionally for a telegram response and if you run this on an energy socket, you will get an exception).
This application is not using MQTT like the one discussed in the other section, but is directly driving the HomeWizard devices.
You have to install the HomeWizard Python library. This can be done by accessing the website https://www.pypi.org and searching for homewizard.
This is the direct link to it: https://pypi.org/project/python-homewizard-energy/ with the pip command to run to get the Python library installed.
There's no need to install asyncio since it's part of the standard Python library now. The one you find on Pypi is obsolete and should NOT be used anymore!
Here's the modified Python code, including the guards around some requests.
import asyncio
import time
from homewizard_energy import HomeWizardEnergyV1
IP_ADDRESS = "192.168.x.x"
def print_message(answer):
print()
print(f"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print(f"Device doesn't support \"{answer}\", skipping...")
print(f"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print()
async def main():
async with HomeWizardEnergyV1(host=IP_ADDRESS) as api:
# Get device information, like firmware version
print()
print(f"Get device information, like firmware version")
print()
device = await api.device()
print(device)
# Get measurements, like energy or water usage
print()
print(f"Get measurements, like energy or water usage")
print()
measurement = await api.measurement()
print(measurement.energy_import_kwh)
if device.supports_telegram():
# Example of getting raw telegram data
print()
print(f"Example of getting raw telegram data")
print()
telegram = await api.telegram()
print(telegram) # Raw P1 meter data
else:
print_message("telegram")
# Get all data and remap v1 data to new v2 structure
print(await api.combined())
if device.supports_state():
# Turn on the Energy Socket outlet
print()
print(f"Turn on the Energy Socket outlet")
print()
await api.state(power_on=False)
time.sleep(2)
await api.state(power_on=True)
time.sleep(2)
await api.state(power_on=False)
time.sleep(2)
await api.state(power_on=True)
else:
print_message("state")
asyncio.run(main())
A bit "rough", but it works like a charm. Also the checks I've added are working great!
So, you now have two ways to access the HomeWizard devices. Up to you to choose one of them...