Repository navigation
Description
Okay, so I'm currently working on rewriting the HA Discovery code from the ground up. Part of this requires me to basically redo the MQTT topics. Right now it's kind of a mess and none of the topics are ideal for Home Assistant (or other home automation platforms).
The first step is to change the topic names and their payload. Here is what I've come up with:
- Power Status Topic
Device Topic/switch => on|off - Power Command Topic
Device Topic/switch/set <= on|true|1|off|false|0 - Color Status Topic
Device Topic/color => R,G,B - Color Command Topic
Device Topic/color/set <= #HEX|R,G,B - Brightness Status Topic
Device Topic/brightness => 0-255 - Brightness Command Topic
Device Topic/brightness/set <= 0-255 - Effect Status Topic
Device Topic/fx => FX Number - Effect Command Topic
Device Topic/fx/set <= FX Number|FX Name - API Response Topic
Device Topic/api => XML API Response - API Command Topic
Device Topic/api/set <= HTTP API Format - Availability Topic
Device Topic/status => online|offline
This puts the topic names in-line with other projects (Espurna, ESPHome, etc.) and makes it easier to integrate into custom code and various home automation platforms without resorting to complex templating or XML decoding (however, because we've retained the API topic, this can still be done for advanced users).
Judging by a look through the issue list, it appears most people are using MQTT for HA Discovery support, which means this change will be transparent for those users (i.e., nothing will break for them and it will just work). This will only be a breaking change for those who manually configure HA, use other home automation platforms or use MQTT as a transport for custom software. I feel this is a very small percentage of use cases and this change will ultimately make it easier to use for them.
I'm interested to hear from anyone using the MQTT support in a non-HA setting (i.e., with custom code, other automation platforms and so forth). Would these topics be sufficient for your use? Is there anything else you'd like to see?
Comments from others (contributors, users and @Aircoookie alike) are welcomed as well!
I've currently got the basics of this implemented in my development fork (not yet published) and it's working well, but I wanted to get a discussion going before I go any further with it.
Edit: Renamed the power topic to switch and added availability to the list of topics. (When the device connects to the broker it will set the status topic to online then register what’s called a “last will”, which allows the broker to take care of setting the status topic to offline for us when the device disconnects.)
Activity
timothybrown commentedon Aug 23, 2019
I should also add that, because of the way I've structured my rewrite, when @Aircoookie finishes support for segments, I'll be able to add segment support into the MQTT code as well. What this means is you could have each segment show up as a separate light in Home Assistant, or you could easily control each segment through MQTT using your custom code. The idea is, each segment would append a number onto the base device topic:
Device Topic/0/[switch|color|brightness|fx|api|status]
Device Topic/0/[switch|color|brightness|fx|api]/set
Device Topic/1/[switch|color|brightness|fx|api|status]
Device Topic/1/[switch|color|brightness|fx|api]/set
Device Topic/2/[switch|color|brightness|fx|api|status]
Device Topic/2/[switch|color|brightness|fx|api]/set
This has a lot of possibilities!
brentbrooks70 commentedon Aug 23, 2019
@timothybrown This would ease my implementation of segment control from the backend platform(QIOT Suite) I am using greatly going forward. I think it would actually make the entire system easier to work with via MQTT.
1a. I guess you could always use the Device Topic/api/set with a T2 so maybe not?
Sorry if it seems like I'm rambling, sort of thinking (out loud) in writing.
Thanks for your work on this and asking for opinions before just making changes!!
Aircoookie commentedon Aug 23, 2019
Hi,
thank you for ewriting the MQTT integration! I absolutely agree, the topics I chose were quite arbitrary. This is often a problem when implementing something you are not an expert with. I definitely agree with bringing the implementation in line with other projects and easing the integration into HA and similar services, so I am very grateful for your help! Your choice of topics seems to make sense for me, this is a lot more transparent and easy to use than the current system. Maybe we can add speed, intensity and palette, but that could also be done at a later stage.
In fact I haven't been in contact with anyone who used MQTT outside of the home automation use case. HA is by far the most common, but there are users of openHAB and domoticz. Of course I will notify them about the breaking change, there is a high chance that your proposal will benefit the complexity of their implementation as well though!
About segments, the ESP basics are already implemented, just the Javascript UI and a few finishing touches are missing. I like your proposal, structuring the topics like that is very logical!
You can take a look at wled19_json.ino to get an idea how to access them. Basically, you can use the
strip.getSegment(index)method to access theSegmentdata object, which contains all the important variables of each segment:strip.getMaxSegments()will be helpful, too. If you want to support setting segment bounds via MQTT (i'm not sure whether that would make sense), usestrip.setSegment(index, start, stop). Let me know if there is anything you need, I'm open to changes to the internal Segment api!A consideration to make with segment support in general is which segment's values to return via the default APIs (XML and MQTT without segment number in topic). I don't think that returning the first segment would make sense for all users, so I'm planning to make this "return segment" user configurable. It is hardcoded to
0right now, but you can already usestrip.getReturnedSegmentId()I have two small questions:
What about the group topics (like /wled/all)? HA probably won't use them (because I assume there are better ways to group devices). Do you think there are use cases for them or should we drop them completely? If we keep them, they should of course mirror the device topic names, but only subscribe to the /set topics, not publish anything.
I'm a little worried that subscribing and publishing to so many topics (especially if we want to support segments) might cause performance issues or even crashing (because of memory overflow by simultaneous requests or similar). We need to make sure that doesn't happen, but for QoS 0 and local MQTT brokers, it could work out.
Thanks once again! Looking forward to hearing from you and let me know if there are any issues!
brentbrooks70 commentedon Aug 23, 2019
@Aircoookie - IMHO you could drop the ALL, topic, every HA setup (including my own) has grouping abilities or if you really needed groups couldn't you configure a UDP port per group and the UDP sync would handle it for you?
timothybrown commentedon Aug 23, 2019
@Aircoookie @brentbrooks70 I’ll respond to the other parts of both your posts later tonight when I get more time. I just wanted to respond to the MQTT group stuff right now while I’m thinking about it.
Yes, I kind of feel that MQTT grouping could be dropped without affecting anyone. As @brentbrooks70 mentioned, we already have the built-in UDP sync functionality that does the same thing, plus most home automation platforms have the ability to group multiple devices into a single “virtual” device.
I’ll give you a good example: My bathroom vanity has three cheap Ai-Light RGBW bulbs installed (running Espurna). Now, I could use Espurna’s MQTT Group feature to have them all listen to the same topic and only add one of them to HA, but because they support HA Discovery, it’s easier for me to simply let HA find all three bulbs and create a light group that presents them as a single virtual bulb.
In fact, I’m hard pressed to think of a setup that UDP Sync or Light Groups wouldn’t cover for WLED. (But of course I don’t know every setup, so if anyone can think of one please share!)
aidbish commentedon Aug 24, 2019
Updating the MQTT topics to work correctly will be a big win especially for those of us running HA. Also agree that the group topic can be removed without any if at all detriment as noted above most automation software allows you to create groups.
Happy to be a willing tester of the implementation
JAMESBOWLER commentedon Aug 24, 2019
I argree its not too hard for me to change. I new around here and use openhab mqtt for control.
Looking at the HA docs for mqtt the JSON schema alows the most features to be used. https://www.home-assistant.io/components/light.mqtt/#json-schema
timothybrown commentedon Aug 24, 2019
@brentbrooks70
Yes, that was my thought as well!
Yes, I could easily add a toggle command if it would be useful for you. I had thought about it, but left it out because I couldn’t immediately come up with a use case for it. (Most home automation software will simply track the state by subscribing to the power topic, or keep track of the state itself and work in a so called optimistic mode.)
Please open an issue for this and I’ll look into adding it to the API! @Aircoookie may have some thoughts on it too.
See my reply to @Aircoookie below.
Yes, I planned on opening an issue about this as well! I’m new as a contributor to the project, so I wanted to get @Aircoookie’s thoughts on why he went with XML instead of JSON for responses. XML is a very verbose schema compared to JSON. We’ve already got the dependency baggage of the JSON library, so why not go all the way and have responses in JSON? It would use less memory, bandwidth and flash, plus it’s easier to encode/decode when writing custom software to control your devices.
My thought is that the JSON API is new and maybe his plan is to eventually switch over to it.
You’re not rambling at all. Personally, I like people thinking out loud like this in a development environment; it’s one of the things that make open source and communities like GitHub so great!
And thank you for the feedback, keep it coming!
@Aircoookie
No worries, at the very least you got basic MQTT support working, which is a lot better than nothing!
Yes, I was thinking about adding topics for speed, intensity and palette too, but I wasn’t sure how useful they would be. The Home Assistant MQTT Light component doesn’t have corresponding controls for those options (other home automation platforms appear to be similar) so they would only be useful in HA if:
However, in all of these cases you can do the same thing by just using the API topic. You’re already implementing custom scripts or automation rules, at which point it’s trivial to just decode and encode for the API topic.
That said, it’s trivial to add them, so if it will make it easier for someone to integrate into their platform or custom code I can add them to the list!
Thanks!
Okay, cool. I’ll start diving into this over the weekend and get a first pass implemented. I may be in contact with some questions as I go!
Yes, I was thinking about this earlier. I think the easiest way to handle this on the MQTT side would be to always include the segment number in the topic path. So, even if the user doesn’t use segments their topic would be Device Topic/0/Command because 0 is the default segment consisting of the entire string of LEDs.
See my earlier reply for more on this.
I don’t think this will be a big issue, but I planned to do some performance profiling and see how far I can push it. The only place we may run into an issue is if the user has a lot of segments. In those cases they might have to use an ESP32.
The alternative is to only have a single topic per segment which would be a JSON input and output. Home Assistant’s MQTT Light component supports three types of schema: default, JSON and template. Right now I’m designing it for the default schema, where the various controls have their own topics. We could switch to the JSON schema, which basically expects a status topic that contains a JSON dictionary, likewise it sends a JSON dictionary to the command topic. Here’s an example:
So each segment would subscribe to one topic and publish to one topic:
Device Topic/Segment => Status JSON Dictionary
Device Topic/Segment/set <= Command JSON Dictionary
However, there's a trade off... These JSON payloads can be hundreds of bytes in size, so we’d need large buffers to hold the incoming data before parsing. Additionally, we’d have to up some of the TCP settings to get it to work reliably.
(You have no idea the hoops I had to jump through to get IR-Blaster to fully support MQTT. IR codes can often be 500+ characters long, that’s not even counting the overhead of putting them in a JSON container!)
It’s doable, but it’ll be a little more complex to implement than the default schema. It really all comes down to where our bottleneck is as to which will perform better.
And thank you for this great project! I’m happy to be able to contribute something.
timothybrown commentedon Aug 24, 2019
Yes, compared to the default schema, the JSON schema gives you a flashing/strobing control and a control to set the transition time between colors. The former isn’t really applicable to WLED and I’m not sure how useful the latter would be.
If you guys would prefer the JSON schema (as described at the end my last post) I could absolutely implement it instead. Technically it would be the most flexible, it’ll just be a lot more complex to implement.
aidbish commentedon Aug 24, 2019
i think the using the json schema would give greater flexibility going forward.
I like the idea of the speed and intensity of an effect being exposed via MQTT as this would for me enable me to set effects with certain speeds in nodered be able to use a zigbee remote to use
brentbrooks70 commentedon Aug 24, 2019
@timothybrown
When you are ready to performance test let me know, I can script some pretty rapid fire calls via QIOT to see how fast it can accept the calls and just how quickly it chews up memory for both platforms.
Very excited about these changes, WLED just keeps getting better!!!
timothybrown commentedon Aug 24, 2019
Yes, I tend to agree, however...
Keep in mind that you’d already be able to do that by just passing the correct command (for speed, intensity or palette) to the API topic. The real question is if it’s worth it to expose those commands as their own unique topics. It seems like in your case either would work, though exposing them as topics would make it simpler for you to implement.
What I’m kind of thinking about right now is maybe going with the topics I outlined in my original post, but changing the API topic to accept a JSON input and provide a JSON output. The JSON schema wouldn’t necessarily conform to the default HA JSON schema, in order to save memory, but would still expose all the available commands. This would be fine as HA would be using the default schema for all the basic functions, the JSON topic would just be there for advanced users or people like you using other platforms.
Hopefully that makes sense, I’m just thinking out loud here.
Awesome, this will be very helpful. I’ve only got two custom lamps that have 70 LEDs in them (that I mainly use with the fire effect), plus an additional strip of 100 on a wall as bias lighting (I’m slowly expanding that one to eventually encircle the entire room). So testing with larger arrays or even larger numbers of smaller arrays will be great. (The latter is important because network traffic can seriously slow things down, especially when you’ve got a bunch of WiFi devices all rapidly sending packets).
Aircoookie commentedon Aug 24, 2019
@brentbrooks70
See #208 !
@timothybrown
Seems like we reached a consensus. Let's drop it! If the user only wants to connect some of the lights to the broker for some reason, they can still use UDP sync!
That is a possibility, although the custom implementation seems more straighforward. Having white value and color temperature do something completely different would confuse new users and it still doesn't cover palettes. That said, WLED does offer RGBW support for WS2813 strips. The bool
useRGBWis true if the user enabled it. The white value is eithercol[3]or for segments, the 8 most significant bytes of the color uint32_t. Maybe it is possible to add that topic when RGBW is enabled, not sure on that one!Agreed! This is a lot easier both for implementation and for the user.
On the topic of JSON vs. topic-per-property scheme types: I think you should implement this however you see fit! If there are any issues down the line we can still switch to the other type.
This exactly! MQTT was implemented before the JSON API and I have not yet connected them. Since JSON has become easier to deal with in just about any modern environment, I think this reorganization is a good opportunity to provide a JSON state API topic for MQTT in addition to or instead of the XML one. This shouldn't be too much work because we can just hook to the provided functions
serializeState(JsonObject)anddeserializeState(JsonObject). Heres the API docAwesome, thanks!
timothybrown commentedon Aug 25, 2019
What do you guys think about adding some general status topics to the list? These would be published under the root device topic only and not duplicated for each segment. Here's an example of what Espurna publishes:
Adding these wouldn't really take up additional resources as we wouldn't be subscribing to them and they could be updated every 60 seconds or during otherwise idle time. While HA and other platforms won't directly use them, I personally find them useful, especially for development or new installations. (I run a custom Python script that tracks this information, which I can review to make sure there's no longterm memory leaks, WiFi issues, stuff like that.)
So, this is what our list looks like now:
Device Topic/Segment/switch => on|off
Device Topic/Segment/switch/set <= on|true|1|off|false|0
Device Topic/Segment/color => R,G,B
Device Topic/Segment/color/set <= #HEX|R,G,B
Device Topic/Segment/brightness => 0-255
Device Topic/Segment/brightness/set <= 0-255
Device Topic/Segment/white => 0-255
Device Topic/Segment/white/set <= 0-255
Device Topic/Segment/fx => FX Number
Device Topic/Segment/fx/set <= FX Number|FX Name
Device Topic/Segment/palette => Palette Name
Device Topic/Segment/palette/set <= Palette Name
Device Topic/Segment/intensity => 0-255
Device Topic/Segment/intensity/set <= 0-255
Device Topic/Segment/speed => 0-255
Device Topic/Segment/speed/set <= 0-255
Device Topic/api => JSON API Response
Device Topic/api/set <= JSON API Format
Device Topic/fw => WLED xx.yy.zz
Device Topic/status => online|offline
Device Topic/vcc => Voltage in mV
Device Topic/rssi => RSSI
Device Topic/mac => MAC Address
Device Topic/host => Hostname
Device Topic/ip => IPv4 Address
Device Topic/ssid => SSID
Device Topic/load => Load Average
Device Topic/mem => Free Memory
Device Topic/uptime => Seconds Since Startup
Device Topic/datetime => Current Date/Time
aidbish commentedon Aug 25, 2019
Yep i like, you could make sensors in HA for things like, fw version, ip address which saves having to load the gui and could be on a glance card or more info card, someone may even make a custom card for WLED that exposes all options.
82 remaining items
brackendegn commentedon Sep 1, 2024
Curious as to what the status of this is? Has there been any progress in being able to get a JSON response back as opposed to XML? I am working on a custom app that would allow for "cloud" access to WLED controllers. Being able to get a state response back in JSON would be very useful for this. I am happy to help in any way I can, though my skills in that area are not very good.
blazoncek commentedon Sep 1, 2024
FYI JSON can get quickly over 10kB while MQTT buffers are usually 1kB.
brackendegn commentedon Sep 3, 2024
I have configured both my mqtt broker and WLED to use a buffer of 3KB and have it sending JSON to the /v topic instead of XML, so far it seems to be working fine
blazoncek commentedon Sep 4, 2024
Use ESP32 and configure 32 segments and use 0_15 branch. Then try again.
JSON size is almost proportional to number of segments.
brackendegn commentedon Sep 4, 2024
I used 3KB as the buffer size, as it was plenty for my needs. I just tested a 10KB buffer and I can get up to 18 segments, but after that it stops sending the state updates through MQTT. Seems to be possibly another limiter in WLED somewhere, but I can't figure out where. The difference in state JSON from 18 to 19 segments is only around 200 Bytes(5.85KB vs. 5.65KB). There seems to be a limiter around 5.7KB.
18 Segments is more than enough for my use case. If this isn't a need for others, I will just leave it as is.
MikeEitel commentedon Jan 1, 2025
Hi
Is there still some work done on the mqtt subject?
And did anyone got the request for a PRESET working?
Tried different ways to write in the /api but none worked also I have
all the usual working fine.I
P.S.
Here a small addon i included in the publish function to get some wifi additional data as I could not get the INFO running,
char subuf2[48];
// Create a standalone XML structure for Wi-Fi data
DynamicBuffer wifiBuf(256); // Allocate a buffer for Wi-Fi XML
bufferPrint wifiPbuf(wifiBuf.data(), wifiBuf.size());
// Build the Wi-Fi XML structure
wifiPbuf.print(F(""));
wifiPbuf.print(F(""));
wifiPbuf.printf_P(PSTR("%s"), WiFi.SSID().c_str());
wifiPbuf.printf_P(PSTR("%d"), WiFi.RSSI());
wifiPbuf.printf_P(PSTR("%u"), WiFi.channel());
wifiPbuf.print(F(""));
// Publish the Wi-Fi XML to a separate MQTT topic
strlcpy(subuf2, mqttDeviceTopic, 33);
strcat_P(subuf2, PSTR("/wifi"));
mqtt->publish(subuf2, 0, retainMqttMsg, wifiBuf.data(), wifiPbuf.size());
artemzhilin82 commentedon Jan 13, 2025
МайкЭйтель I did this for the first PRESET wled/sound/api ={"ps":"1"}
rlimberger commentedon Mar 17, 2025
@blazoncek how did you configure /v to respond in JSON?
blazoncek commentedon Mar 17, 2025
It will not. It only accepts JSON.
brackendegn commentedon Mar 17, 2025
It’s possible. I have it working, but if you go over a certain amount of segments it won’t work. I’ve managed to get it up to 18 segments with no problems. You’ll have to do it on your own version though. I don’t think it’s going to be in the official WLED.
sanderkooger commentedon Dec 11, 2025
Would
Not create an issue for people running RGBW strips. It might be a good idea to think of a method to include white levels.
WouterGritter commentedon Jan 8, 2026
I had some thoughts on this in #4305 which I have closed. I'm not in need of this change anymore, but it might be worth looking at that issue for a possible different use-case of MQTT topics.