2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.netatmo.internal.channelhelper;
15 import static org.openhab.binding.netatmo.internal.NetatmoBindingConstants.*;
17 import java.lang.reflect.InvocationTargetException;
18 import java.lang.reflect.Method;
19 import java.util.Arrays;
20 import java.util.List;
21 import java.util.Optional;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.openhab.binding.netatmo.internal.ChannelTypeUtils;
26 import org.openhab.core.library.types.OnOffType;
27 import org.openhab.core.types.State;
28 import org.openhab.core.types.UnDefType;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
33 * The {@link BatteryHelper} handle specific behavior
34 * of modules using batteries
36 * @author Gaƫl L'hopital - Initial contribution
40 public class BatteryHelper {
41 private final Logger logger = LoggerFactory.getLogger(BatteryHelper.class);
42 private int batteryLow;
44 private @Nullable Object module;
46 public BatteryHelper(String batteryLevels) {
47 List<String> thresholds = Arrays.asList(batteryLevels.split(","));
48 batteryLow = Integer.parseInt(thresholds.get(1));
51 public void setModule(Object module) {
55 public Optional<State> getNAThingProperty(String channelId) {
56 Object module = this.module;
59 if (CHANNEL_BATTERY_LEVEL.equalsIgnoreCase(channelId)
60 || CHANNEL_LOW_BATTERY.equalsIgnoreCase(channelId)) {
62 case CHANNEL_BATTERY_LEVEL:
63 Method getBatteryPercent = module.getClass().getMethod("getBatteryPercent");
64 Integer batteryPercent = (Integer) getBatteryPercent.invoke(module);
65 return Optional.of(ChannelTypeUtils.toDecimalType(batteryPercent));
66 case CHANNEL_LOW_BATTERY:
67 Method getBatteryVp = module.getClass().getMethod("getBatteryVp");
68 Integer batteryVp = (Integer) getBatteryVp.invoke(module);
69 return Optional.of(batteryVp < batteryLow ? OnOffType.ON : OnOffType.OFF);
72 } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
73 | InvocationTargetException e) {
74 logger.warn("The module has no method to access {} property : {}", channelId, e.getMessage());
75 return Optional.of(UnDefType.NULL);
78 return Optional.empty();