Skip to content

Commit 2f8343f

Browse files
authored
Keep resolveConfig in sync (#5776)
Signed-off-by: Leo Siepel <leosiepel@gmail.com>
1 parent 5a98f91 commit 2f8343f

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

bundles/org.openhab.core.thing/src/main/java/org/openhab/core/thing/binding/BaseThingHandler.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,19 @@ public Thing getThing() {
157157
@Override
158158
public void thingUpdated(Thing thing) {
159159
dispose();
160+
setThing(thing);
161+
initialize();
162+
}
163+
164+
/**
165+
* Replaces the {@link Thing} handled by this handler and refreshes its resolved configuration.
166+
* <p>
167+
* Custom {@link #thingUpdated(Thing)} implementations should use this method instead of assigning directly to
168+
* {@link #thing}, so the Thing and resolved configuration remain consistent.
169+
*
170+
* @param thing the updated Thing
171+
*/
172+
protected final void setThing(Thing thing) {
160173
Configuration resolvedConfiguration;
161174
try {
162175
resolvedConfiguration = ConfigUtil.resolveVariables(thing.getConfiguration());
@@ -169,7 +182,6 @@ public void thingUpdated(Thing thing) {
169182
this.thing = thing;
170183
this.resolvedConfig = resolvedConfiguration;
171184
}
172-
initialize();
173185
}
174186

175187
@Override

bundles/org.openhab.core.thing/src/test/java/org/openhab/core/thing/binding/BaseThingHandlerTest.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,10 @@ public void handleCommand(ChannelUID channelUID, Command command) {
6666
public void initialize() {
6767
this.configInInitialize = getConfig();
6868
}
69+
70+
public void replaceThing(Thing thing) {
71+
setThing(thing);
72+
}
6973
}
7074

7175
private static class ConfigUtilAccessor extends ConfigUtil {
@@ -124,6 +128,18 @@ public void testResolvedConfigAfterThingUpdate() {
124128
assertEquals("resolved-bar", handler.getConfig().get("p2"));
125129
}
126130

131+
@Test
132+
public void testResolvedConfigAfterSetThing() {
133+
handler.getConfig();
134+
Thing thing = handler.editThing()
135+
.withConfiguration(new Configuration(Map.of("p1", "${ENV:FOO}", "p2", "${ENV:BAR}"))).build();
136+
137+
handler.replaceThing(thing);
138+
139+
assertEquals("resolved-foo", handler.getConfig().get("p1"));
140+
assertEquals("resolved-bar", handler.getConfig().get("p2"));
141+
}
142+
127143
@Test
128144
public void testResolvedConfigAfterUpdateThing() {
129145
// Action: Update the Thing with new configuration

0 commit comments

Comments
 (0)