HomeHome AutomationHow to use Aqara T1 with ZigBee2MQTT

How to use Aqara T1 with ZigBee2MQTT

Learn how to add Aqara T1 and other in-wall relays to NodeRED and build an awesome dashboard that comes with power consumption data that works for all relays.

After my initial Aqara T1 post, outlining features and connectivity with Aqara’s IP camera and ZigBee hub in one (review), it’s time to go full DIY and connect my trusted CC2531 ZigBee (flash guide) coordinator, Raspberry Pi and ZigBee2MQTT. I’m using NodeRED, as it’s awesome and let me do cool stuff(tutorial for beginners), but you can adapt this guide to Home Assistant too. Yes, I promised the same follow-up for Aqara sensors, and this will be posted soon as well.

Aqara T1 with ZigBee2MQTT

Just like most new ZigBee products, Aqara T1 switches are ZigBee 3.0. My CC2531 is running ZStack 1.2 and it’s not ideal for ZigBee 3.0, but I gave it a go anyway to see if it works. I will be switching to something more powerful soon, but for now, I’m happy to say that Aqara T1 works out of the box with:

  • Z-Stack_Home_1.2 (default) (20201128)
  • Z-Stack_3.0.x (20190425)

Thanks to NodeRED and creative thinking, I will be able to reproduce the Aqara app features, and add a couple of new ones that can be repurposed for other connected relays like Sonoff ZB Mini (review) or Zemismart (review) you could even make this work with WiFi switches, as long as you can make them talk over MQTT (like the ones from Shelly). The features available are:

  • relay toggle actions
  • A simple dashboard GUI
  • power consumption
  • link quality
  • unit temperature

If you read/watched the original review, you know that the no-neutral version of the Aqara T1 comes without the power meter. That’s not a problem as I can take the page from Shelly’s book and add a constant consumption parameter. Just like Shelly did with their Shelly 1L (review) device. I think it’s a great option to have if you are going to add the relay to a device with known power consumption.

Before you continue, do take care, as these switches use mains electricity and this stuff can be dangerous if misused! In doubt, consult a professional.

Adding Aqara T1 to ZigBee2MQTT

The pairing process is simple, press the physical button on the device for 5 seconds and watch the messages in ZigBee2MQTT log via SSH. If this is the first time you are adding a ZigBee device, a detailed tutorial is available here. You should see an entry log showing something like this.

MQTT publish: topic 'zigbee2mqtt/bridge/log', payload '{"message":"interview_successful","meta":{"description":"Aqara single switch module T1 (with neutral)","friendly_name":"0x54ef4410xxxxxxxxf","model":"SSM-U01","supported":true,"vendor":"Xiaomi"},"type":"pairing"}'

Feel free to rename the device in the configuration.yaml, as it will be easier to use it in NodeRED with ZigBee2MQTT. Fortunately, the device is already added to the list of supported devices making my job much easier.

Aqara ZigBee 3.0 line up so far:

Updates

Aqara T1 sends payload every 10 sec, and while all parameters may not show up at first, with time, the device will provide you with a string that looks like this:

{"device_temperature":37,"energy":0,"linkquality":147,"power":9.6,"state":"ON"}

Apart from the state of the relay, we have the information about the temperature (℃) of the relay (which is not available in the Aqara app, and it can be used to monitor the device temp for safety reasons. Power measurement is provided in Watts, but once some time passes, Aqara T1 also supplies the information about the total energy consumption in kWh. There is information about the link quality showing you the ZigBee range as well. Now, that I know all the data, I can start playing with NodeRED.

Aqara T1 in NodeRED

I want to make the flow compatible with both versions of Aqara T1 (L&N, no-neutral) and other connected relays. to make it work, in my setup node, I introduced a default device JSON that you should modify to suit your needs. It will define an object representing the device stored in the flow variable.

var aqara = {   "device_temperature":null,
                "isTempEnabled": true,  
                "energy":0,
                "linkquality":null,
                "power":{
                    "enabled": true,     
                    "current": 0,
                    "hour": [],
                    "day":[],
                    "yesterday": [],
                    "week": [],
                    "month": [],
                    "year" : [],
                    "total": 0
                },
                "state":null
            };

Once you paired your Aqara T1 and linked it to an MQTT node with the correct topic, you will be able to receive the information from your relay. If you are using other relays, make sure that the MQTT messages coming out from the MQTT node are set to match the ones I used in my project. Detailed instructions about the setup are listed later.

Harvesting power info

Aqara T1 submits updates roughly every 10 sec. As I wanted to make this project compatible with other relays as well, I took another approach. Instead of taking the load values every 10 sec, I store the current power draw in my flow variable and recalculate the power use every 60 sec. This approach allows me to reuse the same code for relays without the power metering option.

Instructions to set up your relay are included in the Setup function node in the On Start section. Please make sure to read these carefully.

Depending on the device, the dashboard will display live data directly from the payload of the Aqara T1. If a metric isn’t supported, it will display n/a or 0. Power Calculations group saves the data every minute and passes it forward to create arrays for hourly/day/week/year breakdowns.

Function Node: Calculate
var aqara = flow.get("aqaraT1-LN");
var load = aqara.power.current;
var x = aqara.power.hour;

if(aqara.state === "ON"){
   x.unshift(load);
}
else{
    x.unshift(0);
}
aqara.power.hour = x;
flow.set("aqaraT1-LN", aqara)
return msg;

The process isn’t complicated, as it’s just basic maths, but can look like much at first. The in general, the data is saved to an array that holds info about the recent 60 min. Every hour the data is dumped into an array that stores the information for daily use. It’s the approach that worked really well for my computer dashboard project, so I used it here as well.

This also feeds the data for day/week/month and year. For each time frame, there is a corresponding reset node that saves the data up in the time range and resets the value when needed. You can observe this process in Power Stats reset group.

To display the infomation function Process Power info, gets creative and splits the data into power consumption and power cost. Segregated data is displayed on the dashboard thanks to a small toggle that you can flick.

Function Node: Calculate
var value = flow.get("inCurrency");
var aqara = flow.get("aqaraT1-LN");
var price = global.get("PowerCost");

function add(accumulator, a) {
            return accumulator + a}

//hour
var hour = aqara.power.hour;


//day calculations, saved hourly
var day = aqara.power.day;
if(day[0] > 0){
var dayWatt = (day.reduce(add) + hour.reduce(add))/1000;
var dayCost = (day.reduce(add) + hour.reduce(add))/1000 * price;
}

//yesterday
var yesterday = aqara.power.yesterday;
if(yesterday[0] > 0){
    var yesterdayWatt = yesterday.reduce(add)/1000;
    var yesterdayCost = yesterday.reduce(add)/1000 * price;
}

//week
var week = aqara.power.week;
if(week[0] > 0){
    var weekWatt = (week.reduce(add) + day.reduce(add))/1000;
    var weekCost = (week.reduce(add) + day.reduce(add))/1000 * price;
}
//month
var month = aqara.power.month;
if(month[0] > 0){
    var monthWatt = (month.reduce(add) + day.reduce(add))/1000;
    var monthCost = (month.reduce(add) + day.reduce(add))/1000 * price;
}
//year
var year = aqara.power.year;
if(year[0] > 0){
    var yearWatt = (year.reduce(add) + month.reduce(add) + day.reduce(add))/1000;
    var yearCost = (year.reduce(add) + month.reduce(add) + day.reduce(add))/1000 * price;
}

//total

var total = aqara.power.total;
if(total > 0){
    var totalWatt = total;
    var totalCost = total * price;

}



//calculate cost
if(value === true){
    if(dayCost === undefined){dayCost = 0}
    if(yesterdayCost === undefined){yesterdayCost = 0}
    if(weekCost === undefined){weekCost = 0}
    if(monthCost === undefined){monthCost = 0}
    if(yearCost === undefined){yearCost = 0}
    if(totalCost === undefined){totalCost = 0}
    
    msg.payload =  {"day" : "Today: £"+ dayCost.toFixed(2),
                    "yesterday" : "Yesterday: £"+ yesterdayCost.toFixed(2),
                    "week":  "Last 7 days: £"+ weekCost.toFixed(2),
                    "month": "Month: £"+ monthCost.toFixed(2),
                    "year" : "Year: £"+ yearCost.toFixed(2),
                    "total" : "Total: £"+ totalCost.toFixed(2)};
}
//calculate wattage
else{
    if(dayWatt === undefined){dayWatt = 0}
    if(yesterdayWatt === undefined){yesterdayWatt = 0}
    if(weekWatt === undefined){weekWatt = 0}
    if(monthWatt === undefined){monthWatt = 0}
    if(yearWatt === undefined){yearWatt = 0}
    if(totalWatt === undefined){totalWatt = 0}
    
    msg.payload =  {"day" :  "Today: "+ dayWatt.toFixed(2) + " kWh",
                    "yesterday" : "Yesterday: "+ yesterdayWatt.toFixed(2) +"kWh",
                    "week":  "Last 7 days: "+ weekWatt.toFixed(2) + " kWh",
                    "month":  "Month: "+ monthWatt.toFixed(2) + " kWh",
                    "year" :  "Year: "+ yearWatt.toFixed(2) + " kWh",
                    "total" : "Total: "+ totalWatt.toFixed(2)+ " kWh"};
}

return msg;
[/su_spoiler ]

Grafana and InfluxDB (optional)

To store the data (and display stats and fancy graphs) I use Grafana and InfluxDB integration. If you want to embed cool-looking graphs into the dashboard, read the linked article. If you feel like you don’t need this right now all data points needed to display charts native to the dashboard are stored in the Aqara T1 object.

I’m storing data points as they arrive from the Aqara device. This is saved to the database using node-red-contrib-influxdb. It’s a simple process and requires correct data format:

Function Node: Calculator
var aqara = flow.get("aqaraT1-LN");
var state = msg.payload.state;
var x = 0;

if(state === "ON"){
    x = 1;
}

if(aqara.isTempEnabled === false){msg.payload.device_temperature = "0";}

msg.measurement  = "AqaraT1";
msg.payload = [{
            temperature: msg.payload.device_temperature,
            power: msg.payload.power,
            state: x
},
            
    {location: "office"}
];

return msg;

You will notice that I store the following data:

  • load
  • temperature
  • ON|OFF state as 1|0

While I don’t have any immediate plans for the data, I gathered it could come handy. Storing state data as numbers instead of text or bool, also allows for extra mathematical operations. To access that data back, you can draw it from the InfluxDB directly, but as I promised this integration to be optional, I actually store another set as flow variable. This way you can still have the same functionality without querying the database

Grafana

Grafana displays an embedded chart with 3 buttons responsible for showing you usage graphs with different time ranges: day/week/month. I query the same chart with a slightly different URL each time to get custom time ranges. It’s a neat trick I learned from my experiments with DIY Smart Heating 3.0.

You can customise your chart further by displaying other data points on the same graph (lux values perhaps), change colours or turn the graph into a bar chart. Feel free to experiment and work out what works for you. To make the chart work, copy the embedded version of the chart from the Grafana panel and fill in Grafana URL and panelID in the Compose URL function node in the Grafana section. The detailed tutorial about setting Grafana and InfluxDB is available here.

Function Node: Week
var p_30d  = 1000*60*60*24*30 ; //30 Days
var p_7d  = 1000*60*60*24*7 ; //7 Days
var p_1d   =  1000*60*60*24 ; // 1 Day
var p_hr = 1000*60*60; //1 Hour

var d = new Date();
var current = d.getTime();
var today0h = d.setHours(0,0,0,0); //Timestamp midnight

msg.fromdate = today0h - p_7d
msg.enddate = today0h
return msg
Function Node: Compose URL
var rooms = flow.get("rooms");

//Grafana embeded panel info
var url = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx?orgId=1";  
var panelID = 2;


msg.payload = url + "&refresh=1m&theme=light&from="+ msg.fromdate + "&to="+ msg.enddate + "&panelId="+ panelID;
return msg;

Dashboard tricks

With each tutorial I try to learn something new. This time my focus shifted to a template node in Dashboard. I wanted to have a more control over how dashboard is presented to the user. Thanks to template node, I can arrange the information more efficiently.

I used a template node to display and annimate range icon. Thanks to support for Material icons, I was able change the colours and the icon displayed by the template node with a bit of predefined code submitted to the node based on the value of the link quality.

I used the same approach to serve statistics. A switch toggles values in currency and power used while underlying logic displays live power meter values or estimates if the connected relay supports it. The result: depending on settings a new HTML is generated and send to the dashboard. It works pretty neatly.

Template Node: Cost and Usage

Smart Assistants

There is a slight change this time, as I’m using the latest take on Nora (Smart Nora) to implement Google Assistant. While I don’t have the write up on this yet, the original one is pretty much still relevant. To make it work, I just have to make sure that updates from the switch itself are changed to true/false.

Alexa is done with my usual skill – alexa-home. I completely covered this before, and just like with Google Assistant, I need to translate the message from true/false to ON/OFF. In both cases, changes from voice assistants reflect in the dashboard instantly.

Aqara T1 in other systems

A bunch of you already asked this question: Where else I could use Aqara T1. I have the access to eWeLink based Sonoff ZigBee Bridge (review) which I hacked with Tasmota, a smart Mi Home hub (review) from Xiaomi and Tuya based ZigBee hub (review) I decided to see which ecosystems support it – just in case, you don’t want to go with Aqara app.

EcosystemSupport
Xiaomi Mi Home
Tuya Benexmart Hub✔ (no power metrics and temp)
eWeLink Sonoff ZigBee Bridge✔ (no power metric, temp or feedback from the relay)
Sonoff ZigBee Bridge flashed with Tasmota✔ (requires device setup)

It’s a hit and miss right now with the biggest chances of getting the full compatibility thanks to Flashed Sonoff ZB Bridge (flash guide). For now, I would strongly advise sticking with CC2521 or an equivalent – after all, why pick alternatives when there is a handsome dashboard done for you.

Final Thoughts

I hope you enjoyed this project. Flexible and custom dashboards are what I really like about NodeRED. In this regard, it’s more tailored to your needs than Home Assistant at the cost of increased complexity. I made the tutorial and the project as easy to deploy as possible so you can enjoy this custom widget without the complexity. Let me know what do you think, and if you spot any bugs leave me relevant info so I can fix it. Next up, I will play with Aqara sensors in NodeRED that I got from Aqara. Let me know what would you like to see in the future in this Reddit thread.

Project Download

Download project files here. Bear in mind that Patreon supporters have early access to project files and videos.

PayPal

Nothing says "Thank you" better than keeping my coffee jar topped up!

Patreon

Support me on Patreon and get an early access to tutorial files and videos.

image/svg+xml

Bitcoin (BTC)

Use this QR to keep me caffeinated with BTC: 1FwFqqh71mUTENcRe9q4s9AWFgoc8BA9ZU

Smart Ideas with

Automate your space in with these ecosystems and integrate it with other automation services

client-image
client-image
client-image
client-image
client-image
client-image
client-image
client-image
client-image

Learn NodeRED

NodeRED for beginners: 1. Why do you need a NodeRED server?

0
To server or not to server? That's a very silly question!

Best Automation Projects

Tuya SDK for beginners: Intro to Tuya Cloud API

0
Working with Tuya Cloud API. A guide to Cloud automation for beginners, get started with REST!

NEST your old thermostat under $5

0
Nest-ing up your older thermostat under $5

Nora – Google Assistant in NodeRED

0
Integrate Google Assistant with NodeRED thanks to Nora - NodeRED home automation

DIY Smart Washing Machine – for about 15 bucks!

0
Learn how to add washing machine notifications to your Google Home on the cheap

Sonoff Zigbee Bridge – review

0
Sonoff line up will soon include Sonoff Zigbee Bridge and more Zigbee sensors - here is the first look

Smart Home

Remotes aren’t done with us yet: SwitchBot Remote

0
If you hate having 20 remotes hidden in your sofa, or your parents despise talking to Alexa to turn the lights on - SwitchBot Universal Remote is here to deal with all this!

We’ve seen this before: SwitchBot K10+ PRO

0
This is an odd one. Building on the success of SwitchBot K10+ they released SwitchBot K10+ PRO - but is the experience actually better?

Is this the smart panel we have waited for?

0
ITEAD has released a new smart panel: Sonoff NSPanel Pro 120 - have they learned the lesson from the terrible launch of the original Pro? Let's see what's new.

Aqara FP1E detects motionless humans

0
This isn't exactly a new device, it's an interaction of the original Aqara presence sensor. Aqara FP1E brings Matter, ZigBee and new triggers to your smart home

SwitchBot S10: cleaning re-imagined!

0
SwitchBot S10 promises unattended vacuuming and mopping so you can focus on things you love and care for. Does it deliver?