]> git.basschouten.com Git - openhab-addons.git/blob
393485c82aaef69bfca332f555f152ca23769296
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.senechome.internal;
14
15 import static org.openhab.core.types.RefreshType.REFRESH;
16
17 import java.io.IOException;
18 import java.math.BigDecimal;
19 import java.math.RoundingMode;
20 import java.time.Duration;
21 import java.util.Date;
22 import java.util.concurrent.ExecutionException;
23 import java.util.concurrent.ScheduledFuture;
24 import java.util.concurrent.TimeUnit;
25 import java.util.concurrent.TimeoutException;
26
27 import javax.measure.quantity.Dimensionless;
28 import javax.measure.quantity.ElectricCurrent;
29 import javax.measure.quantity.ElectricPotential;
30 import javax.measure.quantity.Energy;
31 import javax.measure.quantity.Frequency;
32 import javax.measure.quantity.Power;
33
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.eclipse.jetty.client.HttpClient;
37 import org.openhab.binding.senechome.internal.json.SenecHomeResponse;
38 import org.openhab.core.cache.ExpiringCache;
39 import org.openhab.core.library.types.DecimalType;
40 import org.openhab.core.library.types.OnOffType;
41 import org.openhab.core.library.types.QuantityType;
42 import org.openhab.core.library.types.StringType;
43 import org.openhab.core.library.unit.SmartHomeUnits;
44 import org.openhab.core.thing.Channel;
45 import org.openhab.core.thing.ChannelUID;
46 import org.openhab.core.thing.Thing;
47 import org.openhab.core.thing.ThingStatus;
48 import org.openhab.core.thing.ThingStatusDetail;
49 import org.openhab.core.thing.binding.BaseThingHandler;
50 import org.openhab.core.types.Command;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 /**
55  * The {@link SenecHomeHandler} is responsible for handling commands, which are
56  * sent to one of the channels.
57  *
58  * @author Steven Schwarznau - Initial contribution
59  */
60 @NonNullByDefault
61 public class SenecHomeHandler extends BaseThingHandler {
62
63     private final Logger logger = LoggerFactory.getLogger(SenecHomeHandler.class);
64     private final static String VALUE_TYPE_INT = "u3";
65     private final static String VALUE_TYPE_UNSIGNED_INT = "u8";
66     private final static String VALUE_TYPE_FLOAT = "fl";
67
68     private @Nullable ScheduledFuture<?> refreshJob;
69     private @Nullable PowerLimitationStatusDTO limitationStatus = null;
70     private final @Nullable SenecHomeApi senecHomeApi;
71     private SenecHomeConfigurationDTO config = new SenecHomeConfigurationDTO();
72     private final ExpiringCache<Boolean> refreshCache = new ExpiringCache<>(Duration.ofSeconds(5), this::refreshState);
73
74     public SenecHomeHandler(Thing thing, HttpClient httpClient) {
75         super(thing);
76         this.senecHomeApi = new SenecHomeApi(httpClient);
77     }
78
79     @Override
80     public void handleRemoval() {
81         stopJobIfRunning();
82         super.handleRemoval();
83     }
84
85     @Override
86     public void handleCommand(ChannelUID channelUID, Command command) {
87         if (command == REFRESH) {
88             logger.debug("Refreshing {}", channelUID);
89             refresh();
90         } else {
91             logger.trace("The SenecHome-Binding is a read-only binding and can not handle commands");
92         }
93     }
94
95     @Override
96     public void dispose() {
97         stopJobIfRunning();
98         super.dispose();
99     }
100
101     protected void stopJobIfRunning() {
102         final ScheduledFuture<?> refreshJob = this.refreshJob;
103         if (refreshJob != null && !refreshJob.isCancelled()) {
104             refreshJob.cancel(true);
105             this.refreshJob = null;
106         }
107     }
108
109     @Override
110     public void initialize() {
111         config = getConfigAs(SenecHomeConfigurationDTO.class);
112         senecHomeApi.setHostname(config.hostname);
113         refreshJob = scheduler.scheduleWithFixedDelay(this::refresh, 0, config.refreshInterval, TimeUnit.SECONDS);
114         limitationStatus = null;
115     }
116
117     private void refresh() {
118         refreshCache.getValue();
119     }
120
121     public @Nullable Boolean refreshState() {
122         try {
123             SenecHomeResponse response = senecHomeApi.getStatistics();
124             logger.trace("received {}", response);
125
126             BigDecimal pvLimitation = new BigDecimal(100).subtract(getSenecValue(response.limitation.powerLimitation))
127                     .setScale(0, RoundingMode.HALF_UP);
128
129             updateState(SenecHomeBindingConstants.CHANNEL_SENEC_POWER_LIMITATION,
130                     new QuantityType<Dimensionless>(pvLimitation, SmartHomeUnits.PERCENT));
131
132             Channel channelLimitationState = getThing()
133                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_POWER_LIMITATION_STATE);
134             updatePowerLimitationStatus(channelLimitationState,
135                     (100 - pvLimitation.intValue()) <= config.limitationTresholdValue, config.limitationDuration);
136
137             Channel channelConsumption = getThing()
138                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_POWER_CONSUMPTION);
139             updateState(channelConsumption.getUID(),
140                     new QuantityType<Power>(
141                             getSenecValue(response.energy.homePowerConsumption).setScale(2, RoundingMode.HALF_UP),
142                             SmartHomeUnits.WATT));
143
144             Channel channelEnergyProduction = getThing()
145                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_ENERGY_PRODUCTION);
146             updateState(channelEnergyProduction.getUID(),
147                     new QuantityType<Power>(
148                             getSenecValue(response.energy.inverterPowerGeneration).setScale(0, RoundingMode.HALF_UP),
149                             SmartHomeUnits.WATT));
150
151             Channel channelBatteryPower = getThing().getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_BATTERY_POWER);
152             updateState(channelBatteryPower.getUID(),
153                     new QuantityType<Power>(
154                             getSenecValue(response.energy.batteryPower).setScale(2, RoundingMode.HALF_UP),
155                             SmartHomeUnits.WATT));
156
157             Channel channelBatteryFuelCharge = getThing()
158                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_BATTERY_FUEL_CHARGE);
159             updateState(channelBatteryFuelCharge.getUID(),
160                     new QuantityType<Dimensionless>(
161                             getSenecValue(response.energy.batteryFuelCharge).setScale(0, RoundingMode.HALF_UP),
162                             SmartHomeUnits.PERCENT));
163
164             Channel channelGridCurrentPhase1 = getThing()
165                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_GRID_CURRENT_PH1);
166             updateState(channelGridCurrentPhase1.getUID(), new QuantityType<ElectricCurrent>(
167                     getSenecValue(response.grid.currentGridCurrentPerPhase[0]).setScale(2, RoundingMode.HALF_UP),
168                     SmartHomeUnits.AMPERE));
169
170             Channel channelGridCurrentPhase2 = getThing()
171                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_GRID_CURRENT_PH2);
172             updateState(channelGridCurrentPhase2.getUID(), new QuantityType<ElectricCurrent>(
173                     getSenecValue(response.grid.currentGridCurrentPerPhase[1]).setScale(2, RoundingMode.HALF_UP),
174                     SmartHomeUnits.AMPERE));
175
176             Channel channelGridCurrentPhase3 = getThing()
177                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_GRID_CURRENT_PH3);
178             updateState(channelGridCurrentPhase3.getUID(), new QuantityType<ElectricCurrent>(
179                     getSenecValue(response.grid.currentGridCurrentPerPhase[2]).setScale(2, RoundingMode.HALF_UP),
180                     SmartHomeUnits.AMPERE));
181
182             Channel channelGridPowerPhase1 = getThing()
183                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_GRID_POWER_PH1);
184             updateState(channelGridPowerPhase1.getUID(),
185                     new QuantityType<Power>(
186                             getSenecValue(response.grid.currentGridPowerPerPhase[0]).setScale(2, RoundingMode.HALF_UP),
187                             SmartHomeUnits.WATT));
188
189             Channel channelGridPowerPhase2 = getThing()
190                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_GRID_POWER_PH2);
191             updateState(channelGridPowerPhase2.getUID(),
192                     new QuantityType<Power>(
193                             getSenecValue(response.grid.currentGridPowerPerPhase[1]).setScale(2, RoundingMode.HALF_UP),
194                             SmartHomeUnits.WATT));
195
196             Channel channelGridPowerPhase3 = getThing()
197                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_GRID_POWER_PH3);
198             updateState(channelGridPowerPhase3.getUID(),
199                     new QuantityType<Power>(
200                             getSenecValue(response.grid.currentGridPowerPerPhase[2]).setScale(2, RoundingMode.HALF_UP),
201                             SmartHomeUnits.WATT));
202
203             Channel channelGridVoltagePhase1 = getThing()
204                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_GRID_VOLTAGE_PH1);
205             updateState(channelGridVoltagePhase1.getUID(), new QuantityType<ElectricPotential>(
206                     getSenecValue(response.grid.currentGridVoltagePerPhase[0]).setScale(2, RoundingMode.HALF_UP),
207                     SmartHomeUnits.VOLT));
208
209             Channel channelGridVoltagePhase2 = getThing()
210                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_GRID_VOLTAGE_PH2);
211             updateState(channelGridVoltagePhase2.getUID(), new QuantityType<ElectricPotential>(
212                     getSenecValue(response.grid.currentGridVoltagePerPhase[1]).setScale(2, RoundingMode.HALF_UP),
213                     SmartHomeUnits.VOLT));
214
215             Channel channelGridVoltagePhase3 = getThing()
216                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_GRID_VOLTAGE_PH3);
217             updateState(channelGridVoltagePhase3.getUID(), new QuantityType<ElectricPotential>(
218                     getSenecValue(response.grid.currentGridVoltagePerPhase[2]).setScale(2, RoundingMode.HALF_UP),
219                     SmartHomeUnits.VOLT));
220
221             Channel channelGridFrequency = getThing()
222                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_GRID_FREQUENCY);
223             updateState(channelGridFrequency.getUID(),
224                     new QuantityType<Frequency>(
225                             getSenecValue(response.grid.currentGridFrequency).setScale(2, RoundingMode.HALF_UP),
226                             SmartHomeUnits.HERTZ));
227
228             Channel channelBatteryStateValue = getThing()
229                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_BATTERY_STATE_VALUE);
230             updateState(channelBatteryStateValue.getUID(),
231                     new DecimalType(getSenecValue(response.energy.batteryState).intValue()));
232
233             Channel channelLiveBatCharge = getThing()
234                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_LIVE_BAT_CHARGE);
235             updateState(channelLiveBatCharge.getUID(),
236                     new QuantityType<Energy>(
237                             getSenecValue(response.statistics.liveBatCharge).setScale(2, RoundingMode.HALF_UP),
238                             SmartHomeUnits.WATT_HOUR));
239
240             Channel channelLiveBatDischarge = getThing()
241                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_LIVE_BAT_DISCHARGE);
242             updateState(channelLiveBatDischarge.getUID(),
243                     new QuantityType<Energy>(
244                             getSenecValue(response.statistics.liveBatDischarge).setScale(2, RoundingMode.HALF_UP),
245                             SmartHomeUnits.WATT_HOUR));
246
247             Channel channelLiveGridImport = getThing()
248                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_LIVE_GRID_IMPORT);
249             updateState(channelLiveGridImport.getUID(),
250                     new QuantityType<Energy>(
251                             getSenecValue(response.statistics.liveGridImport).setScale(2, RoundingMode.HALF_UP),
252                             SmartHomeUnits.WATT_HOUR));
253
254             Channel channelLiveGridExport = getThing()
255                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_LIVE_GRID_EXPORT);
256             updateState(channelLiveGridExport.getUID(),
257                     new QuantityType<Energy>(
258                             getSenecValue(response.statistics.liveGridExport).setScale(2, RoundingMode.HALF_UP),
259                             SmartHomeUnits.WATT_HOUR));
260
261             Channel channelBatteryVoltage = getThing()
262                     .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_BATTERY_VOLTAGE);
263             updateState(channelBatteryVoltage.getUID(),
264                     new QuantityType<ElectricPotential>(
265                             getSenecValue(response.energy.batteryVoltage).setScale(2, RoundingMode.HALF_UP),
266                             SmartHomeUnits.VOLT));
267
268             Channel channelBatteryState = getThing().getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_BATTERY_STATE);
269             updateBatteryState(channelBatteryState, getSenecValue(response.energy.batteryState).intValue());
270
271             updateGridPowerValues(getSenecValue(response.grid.currentGridValue));
272
273             updateStatus(ThingStatus.ONLINE);
274         } catch (IOException | InterruptedException | TimeoutException | ExecutionException e) {
275             logger.warn("Error refreshing source '{}'", getThing().getUID(), e);
276             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
277                     "Could not connect to Senec web interface:" + e.getMessage());
278         }
279
280         return Boolean.TRUE;
281     }
282
283     protected BigDecimal getSenecValue(String value) {
284         String[] type = value.split("_");
285
286         if (VALUE_TYPE_INT.equalsIgnoreCase(type[0])) {
287             return new BigDecimal(Integer.valueOf(type[1], 16));
288         } else if (VALUE_TYPE_UNSIGNED_INT.equalsIgnoreCase(type[0])) {
289             return new BigDecimal(Integer.valueOf(type[1], 16));
290         } else if (VALUE_TYPE_FLOAT.equalsIgnoreCase(type[0])) {
291             return parseFloatValue(type[1]);
292         } else {
293             logger.warn("Unknown value type [{}]", type[0]);
294         }
295
296         return BigDecimal.ZERO;
297     }
298
299     /**
300      * Parse the hex coded float value of Senec device and return as BigDecimal
301      *
302      * @param value String with hex float
303      * @return BigDecimal with float value
304      */
305     private static BigDecimal parseFloatValue(String value) {
306         // sample: value = 43E26188
307
308         float f = Float.intBitsToFloat(Integer.parseUnsignedInt(value, 16));
309         return new BigDecimal(f);
310     }
311
312     protected void updatePowerLimitationStatus(Channel channel, boolean status, int duration) {
313         if (this.limitationStatus != null) {
314             if (this.limitationStatus.state == status) {
315                 long stateSince = new Date().getTime() - this.limitationStatus.time;
316
317                 if (((int) (stateSince / 1000)) < duration) {
318                     // skip updating state (possible flapping state)
319                     return;
320                 } else {
321                     logger.debug("{} longer than required duration {}", status, duration);
322                 }
323             } else {
324                 this.limitationStatus.state = status;
325                 this.limitationStatus.time = new Date().getTime();
326
327                 // skip updating state (state changed, possible flapping state)
328                 return;
329             }
330         } else {
331             this.limitationStatus = new PowerLimitationStatusDTO();
332             this.limitationStatus.state = status;
333         }
334
335         logger.debug("Updating power limitation state {}", status);
336         updateState(channel.getUID(), status ? OnOffType.ON : OnOffType.OFF);
337     }
338
339     protected void updateBatteryState(Channel channel, int code) {
340         updateState(channel.getUID(), new StringType(SenecBatteryStatus.descriptionFromCode(code)));
341     }
342
343     protected void updateGridPowerValues(BigDecimal gridTotalValue) {
344         BigDecimal gridTotal = gridTotalValue.setScale(2, RoundingMode.HALF_UP);
345
346         Channel channelGridPower = getThing().getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_GRID_POWER);
347         if (channelGridPower != null) {
348             updateState(channelGridPower.getUID(), new QuantityType<Power>(gridTotal, SmartHomeUnits.WATT));
349         }
350
351         Channel channelGridPowerSupply = getThing()
352                 .getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_GRID_POWER_SUPPLY);
353         if (channelGridPowerSupply != null) {
354             BigDecimal gridSupply = gridTotal.compareTo(BigDecimal.ZERO) < 0 ? gridTotal.abs() : BigDecimal.ZERO;
355             updateState(channelGridPowerSupply.getUID(), new QuantityType<Power>(gridSupply, SmartHomeUnits.WATT));
356         }
357
358         Channel channelGridPowerDraw = getThing().getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_GRID_POWER_DRAW);
359         if (channelGridPowerDraw != null) {
360             BigDecimal gridDraw = gridTotal.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : gridTotal.abs();
361             updateState(channelGridPowerDraw.getUID(), new QuantityType<Power>(gridDraw, SmartHomeUnits.WATT));
362         }
363     }
364 }