Hello,
I want to add some more features to my binding on user requests. I am trying to add channels dynamic during runtime. I looked on other bindings how to do that, however it is not working out as expected.
I have a JSON call which retrieves an array of similar objects just with different values. I deserialize them and based on the result I would like to create channels for it. I used the following code to do that
The direction is different for every object, so I use it as identifier by adding the channels:
protected List<Channel> createDynamicChannels() {
SonnenJsonPowerMeterDataDTO[] dataArray = serviceCommunication.getPowerMeterDatas();
List<Channel> channels = new ArrayList<>();
for (SonnenJsonPowerMeterDataDTO data : dataArray) {
String direction = data.getDirection();
channels.add(buildChannel(direction + "_" + SonnenBindingConstants.DIRECTIONSTATE, "String"));
channels.add(buildChannel(direction + "_" + SonnenBindingConstants.AL1STATE, "Number:Power"));
channels.add(buildChannel(direction + "_" + SonnenBindingConstants.AL2STATE, "Number:Power"));
channels.add(buildChannel(direction + "_" + SonnenBindingConstants.AL3STATE, "Number:Power"));
...
This I use to create the channel:
private Channel buildChannel(String channelType, String itemType) {
return ChannelBuilder.create(new ChannelUID(getThing().getUID(), channelType), itemType).build();
}
In the initialization is used:
List<Channel> channels = createDynamicChannels();
ThingBuilder builder = editThing();
builder.withChannels(channels);
updateThing(builder.build());
The effect is that the static channels I have configured in the things.xml are after disappearing and the dynamically created channels are not appearing.
I also tried, which seems to be the better solution, but I never hit changed part:
List<Channel> channels = createDynamicChannels();
ThingBuilder builder = editThing();
boolean changed = false;
for (Channel channel : channels) {
// we only want to add each channel, not replace all of them
if (getThing().getChannel(channel.getUID()) == null) {
builder.withChannel(channel);
changed = true;
}
}
if (changed) {
updateThing(builder.build());
}
As you may see, I am not quite familiar yet with the concept of dynamic channels. Do I need to define the possible channels in the things.xml like I did with the static ones? I tried, did not work either.
Any hints what I am doing wrong or miss?