]> git.basschouten.com Git - openhab-addons.git/blob
0e14c975b9c8cf448cad130b34ed9b7e315bb02a
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.sensebox.internal;
14
15 import static org.openhab.binding.sensebox.internal.SenseBoxBindingConstants.*;
16
17 import java.io.IOException;
18 import java.util.List;
19 import java.util.Properties;
20
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.openhab.binding.sensebox.internal.dto.SenseBoxData;
23 import org.openhab.binding.sensebox.internal.dto.SenseBoxDescriptor;
24 import org.openhab.binding.sensebox.internal.dto.SenseBoxLoc;
25 import org.openhab.binding.sensebox.internal.dto.SenseBoxLocation;
26 import org.openhab.binding.sensebox.internal.dto.SenseBoxSensor;
27 import org.openhab.core.io.net.http.HttpUtil;
28 import org.openhab.core.thing.ThingStatus;
29 import org.osgi.framework.FrameworkUtil;
30 import org.osgi.framework.Version;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 import com.google.gson.Gson;
35 import com.google.gson.JsonSyntaxException;
36
37 /**
38  * The {@link SenseBoxAPIConnection} is responsible for fetching data from the senseBox API server.
39  *
40  * @author Hakan Tandogan - Initial contribution
41  */
42 @NonNullByDefault
43 public class SenseBoxAPIConnection {
44
45     private final Logger logger = LoggerFactory.getLogger(SenseBoxAPIConnection.class);
46
47     private final Gson gson = new Gson();
48
49     private static final Properties HEADERS = new Properties();
50
51     private static final String METHOD = "GET";
52
53     private static final int TIMEOUT = 30 * 1000; // 30 seconds
54
55     public SenseBoxAPIConnection() {
56         Version version = FrameworkUtil.getBundle(this.getClass()).getVersion();
57         HEADERS.put("User-Agent", "openHAB / senseBox binding " + version.toString());
58         logger.trace("Headers: {}", HEADERS);
59     }
60
61     public SenseBoxData reallyFetchDataFromServer(String senseBoxId) {
62         String query = SENSEMAP_API_URL_BASE + "/boxes/" + senseBoxId;
63
64         // the caching layer does not like null values
65         SenseBoxData result = new SenseBoxData();
66
67         String body = null;
68         try {
69             body = HttpUtil.executeUrl(METHOD, query, HEADERS, null, null, TIMEOUT);
70
71             logger.trace("Fetched Data: {}", body);
72             SenseBoxData parsedData = gson.fromJson(body, SenseBoxData.class);
73
74             // Assume all is well at first
75             parsedData.setStatus(ThingStatus.ONLINE);
76
77             // Could perhaps be simplified via triply-nested arrays
78             // http://stackoverflow.com/questions/36946875/how-can-i-parse-geojson-with-gson
79             for (SenseBoxLoc loc : parsedData.getLocs()) {
80                 if (loc.getGeometry() != null) {
81                     List<Double> locationData = loc.getGeometry().getData();
82                     if (locationData != null) {
83                         SenseBoxLocation location = new SenseBoxLocation();
84
85                         if (locationData.size() > 0) {
86                             location.setLongitude(locationData.get(0));
87                         }
88
89                         if (locationData.size() > 1) {
90                             location.setLatitude(locationData.get(1));
91                         }
92
93                         if (locationData.size() > 2) {
94                             location.setHeight(locationData.get(2));
95                         }
96
97                         parsedData.setLocation(location);
98                     }
99                 }
100             }
101
102             for (SenseBoxSensor sensor : parsedData.getSensors()) {
103                 if ("VEML6070".equals(sensor.getSensorType())) {
104                     // "unit" is not nicely comparable, so use sensor type for now
105                     parsedData.setUvIntensity(sensor);
106                 } else if ("SDS 011".equals(sensor.getSensorType())) {
107                     // "unit" is not nicely comparable, neither is type, so use sensor title for now
108                     if ("PM2.5".equals(sensor.getTitle())) {
109                         parsedData.setParticulateMatter2dot5(sensor);
110                     } else if ("PM10".equals(sensor.getTitle())) {
111                         parsedData.setParticulateMatter10(sensor);
112                     } else {
113                         logger.debug("SDS 011 sensor title is {}", sensor.getTitle());
114                     }
115                 } else if ("lx".equals(sensor.getUnit())) {
116                     if (sensor.getLastMeasurement() != null) {
117                         if (!(INVALID_BRIGHTNESS.equals(sensor.getLastMeasurement().getValue()))) {
118                             parsedData.setLuminance(sensor);
119                         }
120                     }
121                 } else if ("Pa".equals(sensor.getUnit()) || "hPa".equals(sensor.getUnit())) {
122                     parsedData.setPressure(sensor);
123                 } else if ("%".equals(sensor.getUnit())) {
124                     parsedData.setHumidity(sensor);
125                 } else if ("°C".equals(sensor.getUnit())) {
126                     parsedData.setTemperature(sensor);
127                 } else {
128                     if (logger.isDebugEnabled()) {
129                         logger.debug("    Sensor: {}", sensor);
130                         logger.debug("    Sensor unit: {}", sensor.getUnit());
131                         logger.debug("    Sensor type: {}", sensor.getSensorType());
132                         logger.debug("    Sensor LM: {}", sensor.getLastMeasurement());
133                         if (sensor.getLastMeasurement() != null) {
134                             logger.debug("    Sensor LM value: {}", sensor.getLastMeasurement().getValue());
135                             logger.debug("    Sensor LM date: '{}'", sensor.getLastMeasurement().getCreatedAt());
136                         }
137                     }
138                 }
139             }
140
141             SenseBoxDescriptor descriptor = new SenseBoxDescriptor();
142             descriptor.setApiUrl(query);
143             String image = parsedData.getImage();
144             if (image != null && !image.isEmpty()) {
145                 descriptor.setImageUrl(SENSEMAP_IMAGE_URL_BASE + "/" + image);
146             }
147             descriptor.setMapUrl(SENSEMAP_MAP_URL_BASE + "/explore/" + senseBoxId);
148             parsedData.setDescriptor(descriptor);
149
150             logger.trace("=================================");
151
152             result = parsedData;
153         } catch (JsonSyntaxException e) {
154             logger.debug("An error occurred while parsing the data into desired class: {} / {} / {}", body,
155                     SenseBoxData.class.getName(), e.getMessage());
156             result.setStatus(ThingStatus.OFFLINE);
157         } catch (IOException e) {
158             logger.debug("IO problems while fetching data: {} / {}", query, e.getMessage());
159             result.setStatus(ThingStatus.OFFLINE);
160         }
161
162         return result;
163     }
164 }