]> git.basschouten.com Git - openhab-addons.git/blob
aa8f1eb493d6ac8f12fd075927c1af80544d2fcf
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.solarlog.internal.handler;
14
15 import java.io.ByteArrayInputStream;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.math.BigDecimal;
19 import java.nio.charset.StandardCharsets;
20 import java.text.ParseException;
21 import java.text.SimpleDateFormat;
22 import java.util.Date;
23 import java.util.concurrent.TimeUnit;
24
25 import org.openhab.binding.solarlog.internal.SolarLogBindingConstants;
26 import org.openhab.binding.solarlog.internal.SolarLogChannel;
27 import org.openhab.binding.solarlog.internal.SolarLogConfig;
28 import org.openhab.core.io.net.http.HttpUtil;
29 import org.openhab.core.library.types.DateTimeType;
30 import org.openhab.core.library.types.DecimalType;
31 import org.openhab.core.library.types.StringType;
32 import org.openhab.core.thing.Channel;
33 import org.openhab.core.thing.ChannelUID;
34 import org.openhab.core.thing.Thing;
35 import org.openhab.core.thing.ThingStatus;
36 import org.openhab.core.thing.ThingStatusDetail;
37 import org.openhab.core.thing.binding.BaseThingHandler;
38 import org.openhab.core.types.Command;
39 import org.openhab.core.types.State;
40 import org.openhab.core.types.UnDefType;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 import com.google.gson.JsonElement;
45 import com.google.gson.JsonObject;
46 import com.google.gson.JsonParser;
47 import com.google.gson.JsonSyntaxException;
48
49 /**
50  * The {@link SolarLogHandler} is responsible for handling commands, which are
51  * sent to one of the channels. It does the "heavy lifting" of connecting to the
52  * Solar-Log, getting the data, parsing it and updating the channels.
53  *
54  * @author Johann Richard - Initial contribution
55  */
56 public class SolarLogHandler extends BaseThingHandler {
57
58     private Logger logger = LoggerFactory.getLogger(SolarLogHandler.class);
59     private SolarLogConfig config;
60
61     private final int timeout = 5000;
62
63     public SolarLogHandler(Thing thing) {
64         super(thing);
65     }
66
67     @Override
68     public void handleCommand(ChannelUID channelUID, Command command) {
69         // Read only
70     }
71
72     @Override
73     public void initialize() {
74         logger.debug("Initializing Solar-Log");
75         config = getConfigAs(SolarLogConfig.class);
76         scheduler.scheduleWithFixedDelay(() -> {
77             logger.debug("Running refresh cycle");
78             try {
79                 refresh();
80                 updateStatus(ThingStatus.ONLINE);
81                 // Very rudimentary Exception differentiation
82             } catch (IOException e) {
83                 logger.debug("Error reading response from Solar-Log", e);
84                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
85                         "Communication error with the device. Please retry later.");
86             } catch (JsonSyntaxException je) {
87                 logger.warn("Invalid JSON when refreshing source {}: {}", getThing().getUID(), je.getMessage());
88             } catch (Exception e) {
89                 logger.warn("Error refreshing source {}: {}", getThing().getUID(), e.getMessage(), e);
90             }
91         }, 0, config.refreshInterval < 15 ? 15 : config.refreshInterval, TimeUnit.SECONDS); // Minimum interval is 15 s
92     }
93
94     private void refresh() throws Exception {
95         // Get the JSON - somehow
96         logger.trace("Starting refresh handler");
97         String httpMethod = "POST";
98         String url = config.url + "/getjp";
99         String content = "{\"801\":{\"170\":null}}";
100         InputStream stream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
101
102         logger.debug("Attempting to load data from {} with parameter {}", url, content);
103         String response = HttpUtil.executeUrl(httpMethod, url, stream, null, timeout);
104         JsonElement solarLogDataElement = JsonParser.parseString(response);
105         JsonObject solarLogData = solarLogDataElement.getAsJsonObject();
106
107         // Check whether the data is well-formed
108         if (solarLogData.has(SolarLogBindingConstants.SOLARLOG_JSON_ROOT)) {
109             solarLogData = solarLogData.getAsJsonObject(SolarLogBindingConstants.SOLARLOG_JSON_ROOT);
110             logger.trace("Found root node in Solar-Log data. Attempting to read data");
111             if (solarLogData.has(SolarLogBindingConstants.SOLARLOG_JSON_PROPERTIES)) {
112                 solarLogData = solarLogData.getAsJsonObject(SolarLogBindingConstants.SOLARLOG_JSON_PROPERTIES);
113
114                 for (SolarLogChannel channelConfig : SolarLogChannel.values()) {
115                     if (solarLogData.has(channelConfig.getIndex())) {
116                         String value = solarLogData.get(channelConfig.getIndex()).getAsString();
117                         Channel channel = getThing().getChannel(channelConfig.getId());
118                         State state = getState(value, channelConfig);
119                         if (channel != null) {
120                             logger.trace("Update channel state: {}", state);
121                             updateState(channel.getUID(), state);
122                         }
123                     } else {
124                         logger.debug("Error refreshing source {}: {}", getThing().getUID(), channelConfig.getId());
125                     }
126                 }
127             }
128         } else {
129             logger.warn("Data retrieval failed, no data returned {}", response);
130         }
131     }
132
133     private State getState(String value, SolarLogChannel type) {
134         switch (type) {
135             // Only DateTime channel
136             case CHANNEL_LASTUPDATETIME:
137                 try {
138                     logger.trace("Parsing date {}", value);
139                     try {
140                         Date date = new SimpleDateFormat("dd.MM.yy HH:mm:ss").parse(value);
141                         SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");// dd/MM/yyyy
142                         String strDate = sdfDate.format(date);
143
144                         logger.trace("Parsing date successful. Returning date. {}", new DateTimeType(strDate));
145                         return new DateTimeType(strDate);
146                     } catch (ParseException fpe) {
147                         logger.trace("Parsing date failed. Returning string.", fpe);
148                         return new StringType(value);
149                     }
150                 } catch (IllegalArgumentException e) {
151                     logger.warn("Parsing date failed. Returning nothing", e);
152                     return UnDefType.UNDEF;
153                 }
154                 // All other channels should be numbers
155             default:
156                 try {
157                     logger.trace("Parsing number {}", value);
158                     return new DecimalType(new BigDecimal(value));
159                 } catch (NumberFormatException e) {
160                     // Log a warning and return UNDEF
161                     logger.warn("Parsing number failed. Returning nothing", e);
162                     return UnDefType.UNDEF;
163                 }
164         }
165     }
166 }