]> git.basschouten.com Git - openhab-addons.git/blob
3094c62827d46c7e6f949137ae05c44388da8628
[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.tibber.internal.handler;
14
15 import static org.openhab.binding.tibber.internal.TibberBindingConstants.*;
16
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.math.BigDecimal;
20 import java.net.URI;
21 import java.net.URISyntaxException;
22 import java.util.Properties;
23 import java.util.concurrent.Future;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
26
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.eclipse.jetty.client.HttpClient;
30 import org.eclipse.jetty.http.HttpHeader;
31 import org.eclipse.jetty.util.ssl.SslContextFactory;
32 import org.eclipse.jetty.websocket.api.Session;
33 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
34 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
35 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
36 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
37 import org.eclipse.jetty.websocket.api.annotations.WebSocket;
38 import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
39 import org.eclipse.jetty.websocket.client.WebSocketClient;
40 import org.openhab.binding.tibber.internal.config.TibberConfiguration;
41 import org.openhab.core.io.net.http.HttpUtil;
42 import org.openhab.core.library.types.DateTimeType;
43 import org.openhab.core.library.types.DecimalType;
44 import org.openhab.core.library.types.QuantityType;
45 import org.openhab.core.library.types.StringType;
46 import org.openhab.core.library.unit.Units;
47 import org.openhab.core.thing.ChannelUID;
48 import org.openhab.core.thing.Thing;
49 import org.openhab.core.thing.ThingStatus;
50 import org.openhab.core.thing.ThingStatusDetail;
51 import org.openhab.core.thing.ThingStatusInfo;
52 import org.openhab.core.thing.binding.BaseThingHandler;
53 import org.openhab.core.types.Command;
54 import org.openhab.core.types.RefreshType;
55 import org.osgi.framework.FrameworkUtil;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 import com.google.gson.JsonArray;
60 import com.google.gson.JsonObject;
61 import com.google.gson.JsonParser;
62 import com.google.gson.JsonSyntaxException;
63
64 /**
65  * The {@link TibberHandler} is responsible for handling queries to/from Tibber API.
66  *
67  * @author Stian Kjoglum - Initial contribution
68  */
69 @NonNullByDefault
70 public class TibberHandler extends BaseThingHandler {
71     private static final int REQUEST_TIMEOUT = (int) TimeUnit.SECONDS.toMillis(20);
72     private final Logger logger = LoggerFactory.getLogger(TibberHandler.class);
73     private final Properties httpHeader = new Properties();
74     private TibberConfiguration tibberConfig = new TibberConfiguration();
75     private @Nullable SslContextFactory sslContextFactory;
76     private @Nullable TibberWebSocketListener socket;
77     private @Nullable Session session;
78     private @Nullable WebSocketClient client;
79     private @Nullable ScheduledFuture<?> pollingJob;
80     private @Nullable Future<?> sessionFuture;
81     private String rtEnabled = "false";
82     private @Nullable String subscriptionURL;
83     private @Nullable String versionString;
84
85     public TibberHandler(Thing thing) {
86         super(thing);
87     }
88
89     @Override
90     public void initialize() {
91         updateStatus(ThingStatus.UNKNOWN);
92         tibberConfig = getConfigAs(TibberConfiguration.class);
93
94         versionString = FrameworkUtil.getBundle(this.getClass()).getVersion().toString();
95         logger.debug("Binding version: {}", versionString);
96
97         getTibberParameters();
98         startRefresh(tibberConfig.getRefresh());
99     }
100
101     @Override
102     public void handleCommand(ChannelUID channelUID, Command command) {
103         if (command instanceof RefreshType) {
104             startRefresh(tibberConfig.getRefresh());
105         } else {
106             logger.debug("Tibber API is read-only and does not handle commands");
107         }
108     }
109
110     public void getTibberParameters() {
111         String response = "";
112         try {
113             httpHeader.put("cache-control", "no-cache");
114             httpHeader.put("content-type", JSON_CONTENT_TYPE);
115             httpHeader.put(HttpHeader.USER_AGENT.asString(),
116                     "openHAB/Tibber " + versionString + " Tibber driver " + TIBBER_DRIVER);
117             httpHeader.put(HttpHeader.AUTHORIZATION.asString(), "Bearer " + tibberConfig.getToken());
118
119             TibberPriceConsumptionHandler tibberQuery = new TibberPriceConsumptionHandler();
120             InputStream connectionStream = tibberQuery.connectionInputStream(tibberConfig.getHomeid());
121             response = HttpUtil.executeUrl("POST", BASE_URL, httpHeader, connectionStream, null, REQUEST_TIMEOUT);
122
123             if (!response.contains("error") && !response.contains("<html>")) {
124                 updateStatus(ThingStatus.ONLINE);
125                 getURLInput(BASE_URL);
126
127                 InputStream inputStream = tibberQuery.getRealtimeInputStream(tibberConfig.getHomeid());
128                 String jsonResponse = HttpUtil.executeUrl("POST", BASE_URL, httpHeader, inputStream, null,
129                         REQUEST_TIMEOUT);
130
131                 JsonObject object = (JsonObject) JsonParser.parseString(jsonResponse);
132                 rtEnabled = object.getAsJsonObject("data").getAsJsonObject("viewer").getAsJsonObject("home")
133                         .getAsJsonObject("features").get("realTimeConsumptionEnabled").toString();
134
135                 if ("true".equals(rtEnabled)) {
136                     logger.debug("Pulse associated with HomeId: Live stream will be started");
137
138                     InputStream wsURL = tibberQuery.getWebsocketUrl();
139                     String wsResponse = HttpUtil.executeUrl("POST", BASE_URL, httpHeader, wsURL, null, REQUEST_TIMEOUT);
140
141                     JsonObject wsobject = (JsonObject) JsonParser.parseString(wsResponse);
142                     subscriptionURL = wsobject.getAsJsonObject("data").getAsJsonObject("viewer")
143                             .get("websocketSubscriptionUrl").toString().replaceAll("^\"|\"$", "");
144                     logger.debug("Subscribing to: {}", subscriptionURL);
145
146                     open();
147                 } else {
148                     logger.debug("No Pulse associated with HomeId: No live stream will be started");
149                 }
150             } else {
151                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
152                         "Problems connecting/communicating with server: " + response);
153             }
154         } catch (IOException | JsonSyntaxException e) {
155             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
156         }
157     }
158
159     public void getURLInput(String url) throws IOException {
160         String jsonResponse = "";
161         TibberPriceConsumptionHandler tibberQuery = new TibberPriceConsumptionHandler();
162
163         InputStream inputStream = tibberQuery.getInputStream(tibberConfig.getHomeid());
164         jsonResponse = HttpUtil.executeUrl("POST", url, httpHeader, inputStream, null, REQUEST_TIMEOUT);
165         logger.debug("API response: {}", jsonResponse);
166
167         if (!jsonResponse.contains("error") && !jsonResponse.contains("<html>")) {
168             if (getThing().getStatus() == ThingStatus.OFFLINE || getThing().getStatus() == ThingStatus.INITIALIZING) {
169                 updateStatus(ThingStatus.ONLINE);
170             }
171
172             JsonObject rootJsonObject = (JsonObject) JsonParser.parseString(jsonResponse);
173
174             if (jsonResponse.contains("total")) {
175                 try {
176                     JsonObject current = rootJsonObject.getAsJsonObject("data").getAsJsonObject("viewer")
177                             .getAsJsonObject("home").getAsJsonObject("currentSubscription").getAsJsonObject("priceInfo")
178                             .getAsJsonObject("current");
179
180                     updateState(CURRENT_TOTAL, new DecimalType(current.get("total").toString()));
181                     String timestamp = current.get("startsAt").toString().substring(1, 20);
182                     updateState(CURRENT_STARTSAT, new DateTimeType(timestamp));
183                     updateState(CURRENT_LEVEL,
184                             new StringType(current.get("level").toString().replaceAll("^\"|\"$", "")));
185
186                     JsonArray tomorrow = rootJsonObject.getAsJsonObject("data").getAsJsonObject("viewer")
187                             .getAsJsonObject("home").getAsJsonObject("currentSubscription").getAsJsonObject("priceInfo")
188                             .getAsJsonArray("tomorrow");
189                     updateState(TOMORROW_PRICES, new StringType(tomorrow.toString()));
190                 } catch (JsonSyntaxException e) {
191                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
192                             "Error communicating with Tibber API: " + e.getMessage());
193                 }
194             }
195             if (jsonResponse.contains("daily") && !jsonResponse.contains("\"daily\":{\"nodes\":[]")
196                     && !jsonResponse.contains("\"daily\":null")) {
197                 try {
198                     JsonObject myObject = (JsonObject) rootJsonObject.getAsJsonObject("data").getAsJsonObject("viewer")
199                             .getAsJsonObject("home").getAsJsonObject("daily").getAsJsonArray("nodes").get(0);
200
201                     String timestampDailyFrom = myObject.get("from").toString().substring(1, 20);
202                     updateState(DAILY_FROM, new DateTimeType(timestampDailyFrom));
203
204                     String timestampDailyTo = myObject.get("to").toString().substring(1, 20);
205                     updateState(DAILY_TO, new DateTimeType(timestampDailyTo));
206
207                     updateChannel(DAILY_COST, myObject.get("cost").toString());
208                     updateChannel(DAILY_CONSUMPTION, myObject.get("consumption").toString());
209                 } catch (JsonSyntaxException e) {
210                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
211                             "Error communicating with Tibber API: " + e.getMessage());
212                 }
213             }
214             if (jsonResponse.contains("hourly") && !jsonResponse.contains("\"hourly\":{\"nodes\":[]")
215                     && !jsonResponse.contains("\"hourly\":null")) {
216                 try {
217                     JsonObject myObject = (JsonObject) rootJsonObject.getAsJsonObject("data").getAsJsonObject("viewer")
218                             .getAsJsonObject("home").getAsJsonObject("hourly").getAsJsonArray("nodes").get(0);
219
220                     String timestampHourlyFrom = myObject.get("from").toString().substring(1, 20);
221                     updateState(HOURLY_FROM, new DateTimeType(timestampHourlyFrom));
222
223                     String timestampHourlyTo = myObject.get("to").toString().substring(1, 20);
224                     updateState(HOURLY_TO, new DateTimeType(timestampHourlyTo));
225
226                     updateChannel(HOURLY_COST, myObject.get("cost").toString());
227                     updateChannel(HOURLY_CONSUMPTION, myObject.get("consumption").toString());
228                 } catch (JsonSyntaxException e) {
229                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
230                             "Error communicating with Tibber API: " + e.getMessage());
231                 }
232             }
233         } else if (jsonResponse.contains("error")) {
234             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
235                     "Error in response from Tibber API: " + jsonResponse);
236             try {
237                 Thread.sleep(300 * 1000);
238                 return;
239             } catch (InterruptedException e) {
240                 logger.debug("Tibber OFFLINE, attempting thread sleep: {}", e.getMessage());
241             }
242         } else {
243             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
244                     "Unexpected response from Tibber: " + jsonResponse);
245             try {
246                 Thread.sleep(300 * 1000);
247                 return;
248             } catch (InterruptedException e) {
249                 logger.debug("Tibber OFFLINE, attempting thread sleep: {}", e.getMessage());
250             }
251         }
252     }
253
254     public void startRefresh(int refresh) {
255         if (pollingJob == null) {
256             pollingJob = scheduler.scheduleWithFixedDelay(() -> {
257                 try {
258                     updateRequest();
259                 } catch (IOException e) {
260                     logger.warn("IO Exception: {}", e.getMessage());
261                 }
262             }, 1, refresh, TimeUnit.MINUTES);
263         }
264     }
265
266     public void updateRequest() throws IOException {
267         getURLInput(BASE_URL);
268         if ("true".equals(rtEnabled) && !isConnected()) {
269             logger.debug("Attempting to reopen Websocket connection");
270             open();
271         }
272     }
273
274     public void updateChannel(String channelID, String channelValue) {
275         if (!channelValue.contains("null")) {
276             if (channelID.contains("consumption") || channelID.contains("Consumption")
277                     || channelID.contains("accumulatedProduction")) {
278                 updateState(channelID, new QuantityType<>(new BigDecimal(channelValue), Units.KILOWATT_HOUR));
279             } else if (channelID.contains("power") || channelID.contains("Power")) {
280                 updateState(channelID, new QuantityType<>(new BigDecimal(channelValue), Units.WATT));
281             } else if (channelID.contains("voltage")) {
282                 updateState(channelID, new QuantityType<>(new BigDecimal(channelValue), Units.VOLT));
283             } else if (channelID.contains("current")) {
284                 updateState(channelID, new QuantityType<>(new BigDecimal(channelValue), Units.AMPERE));
285             } else {
286                 updateState(channelID, new DecimalType(channelValue));
287             }
288         }
289     }
290
291     public void thingStatusChanged(ThingStatusInfo thingStatusInfo) {
292         logger.debug("Thing Status updated to {} for device: {}", thingStatusInfo.getStatus(), getThing().getUID());
293         if (thingStatusInfo.getStatus() != ThingStatus.ONLINE) {
294             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
295                     "Unable to communicate with Tibber API");
296         }
297     }
298
299     @Override
300     public void dispose() {
301         ScheduledFuture<?> pollingJob = this.pollingJob;
302         if (pollingJob != null) {
303             pollingJob.cancel(true);
304             this.pollingJob = null;
305         }
306         if (isConnected()) {
307             close();
308             WebSocketClient client = this.client;
309             if (client != null) {
310                 try {
311                     logger.debug("DISPOSE - Stopping and Terminating Websocket connection");
312                     client.stop();
313                 } catch (Exception e) {
314                     logger.warn("Websocket Client Stop Exception: {}", e.getMessage());
315                 }
316                 client.destroy();
317                 this.client = null;
318             }
319         }
320         super.dispose();
321     }
322
323     public void open() {
324         WebSocketClient client = this.client;
325         if (client == null || !client.isRunning() || !isConnected()) {
326             if (client != null) {
327                 try {
328                     client.stop();
329                 } catch (Exception e) {
330                     logger.warn("OPEN FRAME - Failed to stop websocket client: {}", e.getMessage());
331                 }
332                 client.destroy();
333             }
334             sslContextFactory = new SslContextFactory.Client(true);
335             sslContextFactory.setTrustAll(true);
336             sslContextFactory.setEndpointIdentificationAlgorithm(null);
337
338             client = new WebSocketClient(new HttpClient(sslContextFactory));
339             client.setMaxIdleTimeout(30 * 1000);
340             this.client = client;
341
342             TibberWebSocketListener socket = this.socket;
343             if (socket == null) {
344                 logger.debug("New socket being created");
345                 socket = new TibberWebSocketListener();
346                 this.socket = socket;
347             }
348
349             ClientUpgradeRequest newRequest = new ClientUpgradeRequest();
350             newRequest.setHeader(HttpHeader.USER_AGENT.asString(),
351                     "openHAB/Tibber " + versionString + " Tibber driver " + TIBBER_DRIVER);
352             newRequest.setHeader(HttpHeader.AUTHORIZATION.asString(), "Bearer " + tibberConfig.getToken());
353             newRequest.setSubProtocols("graphql-transport-ws");
354
355             try {
356                 logger.debug("Starting Websocket connection");
357                 client.start();
358             } catch (Exception e) {
359                 logger.warn("Websocket Start Exception: {}", e.getMessage());
360             }
361             try {
362                 logger.debug("Connecting Websocket connection");
363                 sessionFuture = client.connect(socket, new URI(subscriptionURL), newRequest);
364                 try {
365                     Thread.sleep(10 * 1000);
366                 } catch (InterruptedException e) {
367                 }
368                 if (!isConnected()) {
369                     logger.warn("Unable to establish websocket session - Reattempting connection on next refresh");
370                 } else {
371                     logger.debug("Websocket session established");
372                 }
373             } catch (IOException e) {
374                 logger.warn("Websocket Connect Exception: {}", e.getMessage());
375             } catch (URISyntaxException e) {
376                 logger.warn("Websocket URI Exception: {}", e.getMessage());
377             }
378         } else {
379             logger.warn("Open: Websocket client already running");
380         }
381     }
382
383     public void close() {
384         Session session = this.session;
385         if (session != null) {
386             String disconnect = "{\"type\":\"connection_terminate\",\"payload\":null}";
387             try {
388                 TibberWebSocketListener socket = this.socket;
389                 if (socket != null) {
390                     logger.debug("Sending websocket disconnect message");
391                     socket.sendMessage(disconnect);
392                 } else {
393                     logger.warn("Socket unable to send disconnect message: Socket is null");
394                 }
395             } catch (IOException e) {
396                 logger.warn("Websocket Close Exception: {}", e.getMessage());
397             }
398             try {
399                 session.close();
400             } catch (Exception e) {
401                 logger.warn("Unable to disconnect session");
402             }
403             this.session = null;
404             this.socket = null;
405         }
406         Future<?> sessionFuture = this.sessionFuture;
407         if (sessionFuture != null && !sessionFuture.isDone()) {
408             sessionFuture.cancel(true);
409         }
410         WebSocketClient client = this.client;
411         if (client != null) {
412             try {
413                 client.stop();
414             } catch (Exception e) {
415                 logger.warn("CLOSE FRAME - Failed to stop websocket client: {}", e.getMessage());
416             }
417             client.destroy();
418         }
419     }
420
421     public boolean isConnected() {
422         Session session = this.session;
423         return session != null && session.isOpen();
424     }
425
426     @WebSocket
427     @NonNullByDefault
428     public class TibberWebSocketListener {
429
430         @OnWebSocketConnect
431         public void onConnect(Session wssession) {
432             TibberHandler.this.session = wssession;
433             TibberWebSocketListener socket = TibberHandler.this.socket;
434             String connection = "{\"type\":\"connection_init\", \"payload\":{\"token\":\"" + tibberConfig.getToken()
435                     + "\"}}";
436             try {
437                 if (socket != null) {
438                     logger.debug("Sending websocket connect message");
439                     socket.sendMessage(connection);
440                 } else {
441                     logger.debug("Socket unable to send connect message: Socket is null");
442                 }
443             } catch (IOException e) {
444                 logger.warn("Send Message Exception: {}", e.getMessage());
445             }
446         }
447
448         @OnWebSocketClose
449         public void onClose(int statusCode, String reason) {
450             logger.debug("Closing a WebSocket due to {}", reason);
451             WebSocketClient client = TibberHandler.this.client;
452             if (client != null && client.isRunning()) {
453                 try {
454                     logger.debug("ONCLOSE - Stopping and Terminating Websocket connection");
455                     client.stop();
456                 } catch (Exception e) {
457                     logger.warn("Websocket Client Stop Exception: {}", e.getMessage());
458                 }
459             }
460         }
461
462         @OnWebSocketError
463         public void onWebSocketError(Throwable e) {
464             String message = e.getMessage();
465             logger.debug("Error during websocket communication: {}", message);
466             close();
467         }
468
469         @OnWebSocketMessage
470         public void onMessage(String message) {
471             if (message.contains("connection_ack")) {
472                 logger.debug("Connected to Server");
473                 startSubscription();
474             } else if (message.contains("error") || message.contains("terminate")) {
475                 logger.debug("Error/terminate received from server: {}", message);
476                 close();
477             } else if (message.contains("liveMeasurement")) {
478                 JsonObject object = (JsonObject) JsonParser.parseString(message);
479                 JsonObject myObject = object.getAsJsonObject("payload").getAsJsonObject("data")
480                         .getAsJsonObject("liveMeasurement");
481                 if (myObject.has("timestamp")) {
482                     String liveTimestamp = myObject.get("timestamp").toString().substring(1, 20);
483                     updateState(LIVE_TIMESTAMP, new DateTimeType(liveTimestamp));
484                 }
485                 if (myObject.has("power")) {
486                     updateChannel(LIVE_POWER, myObject.get("power").toString());
487                 }
488                 if (myObject.has("lastMeterConsumption")) {
489                     updateChannel(LIVE_LASTMETERCONSUMPTION, myObject.get("lastMeterConsumption").toString());
490                 }
491                 if (myObject.has("accumulatedConsumption")) {
492                     updateChannel(LIVE_ACCUMULATEDCONSUMPTION, myObject.get("accumulatedConsumption").toString());
493                 }
494                 if (myObject.has("accumulatedCost")) {
495                     updateChannel(LIVE_ACCUMULATEDCOST, myObject.get("accumulatedCost").toString());
496                 }
497                 if (myObject.has("currency")) {
498                     updateState(LIVE_CURRENCY, new StringType(myObject.get("currency").toString()));
499                 }
500                 if (myObject.has("minPower")) {
501                     updateChannel(LIVE_MINPOWER, myObject.get("minPower").toString());
502                 }
503                 if (myObject.has("averagePower")) {
504                     updateChannel(LIVE_AVERAGEPOWER, myObject.get("averagePower").toString());
505                 }
506                 if (myObject.has("maxPower")) {
507                     updateChannel(LIVE_MAXPOWER, myObject.get("maxPower").toString());
508                 }
509                 if (myObject.has("voltagePhase1")) {
510                     updateChannel(LIVE_VOLTAGE1, myObject.get("voltagePhase1").toString());
511                 }
512                 if (myObject.has("voltagePhase2")) {
513                     updateChannel(LIVE_VOLTAGE2, myObject.get("voltagePhase2").toString());
514                 }
515                 if (myObject.has("voltagePhase3")) {
516                     updateChannel(LIVE_VOLTAGE3, myObject.get("voltagePhase3").toString());
517                 }
518                 if (myObject.has("currentL1")) {
519                     updateChannel(LIVE_CURRENT1, myObject.get("currentL1").toString());
520                 }
521                 if (myObject.has("currentL2")) {
522                     updateChannel(LIVE_CURRENT2, myObject.get("currentL2").toString());
523                 }
524                 if (myObject.has("currentL3")) {
525                     updateChannel(LIVE_CURRENT3, myObject.get("currentL3").toString());
526                 }
527                 if (myObject.has("powerProduction")) {
528                     updateChannel(LIVE_POWERPRODUCTION, myObject.get("powerProduction").toString());
529                 }
530                 if (myObject.has("accumulatedProduction")) {
531                     updateChannel(LIVE_ACCUMULATEDPRODUCTION, myObject.get("accumulatedProduction").toString());
532                 }
533                 if (myObject.has("minPowerProduction")) {
534                     updateChannel(LIVE_MINPOWERPRODUCTION, myObject.get("minPowerProduction").toString());
535                 }
536                 if (myObject.has("maxPowerProduction")) {
537                     updateChannel(LIVE_MAXPOWERPRODUCTION, myObject.get("maxPowerProduction").toString());
538                 }
539             } else {
540                 logger.debug("Unknown live response from Tibber");
541             }
542         }
543
544         private void sendMessage(String message) throws IOException {
545             logger.debug("Send message: {}", message);
546             Session session = TibberHandler.this.session;
547             if (session != null) {
548                 session.getRemote().sendString(message);
549             }
550         }
551
552         public void startSubscription() {
553             String query = "{\"id\":\"1\",\"type\":\"subscribe\",\"payload\":{\"variables\":{},\"extensions\":{},\"operationName\":null,\"query\":\"subscription {\\n liveMeasurement(homeId:\\\""
554                     + tibberConfig.getHomeid()
555                     + "\\\") {\\n timestamp\\n power\\n lastMeterConsumption\\n accumulatedConsumption\\n accumulatedCost\\n currency\\n minPower\\n averagePower\\n maxPower\\n"
556                     + "voltagePhase1\\n voltagePhase2\\n voltagePhase3\\n currentL1\\n currentL2\\n currentL3\\n powerProduction\\n accumulatedProduction\\n minPowerProduction\\n maxPowerProduction\\n }\\n }\\n\"}}";
557             try {
558                 TibberWebSocketListener socket = TibberHandler.this.socket;
559                 if (socket != null) {
560                     socket.sendMessage(query);
561                 } else {
562                     logger.debug("Socket unable to send subscription message: Socket is null");
563                 }
564             } catch (IOException e) {
565                 logger.warn("Send Message Exception: {}", e.getMessage());
566             }
567         }
568     }
569 }