Renamed Tibber plugin name

This commit is contained in:
Ziver Koc 2025-10-23 23:30:55 +02:00
parent 21a672acf4
commit c96a00333b
9 changed files with 28 additions and 42 deletions

View file

@ -0,0 +1,3 @@
dependencies {
implementation project(':hal-core')
}

View file

@ -0,0 +1,168 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2025 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.plugin.vendor.tibber;
import se.hal.HalContext;
import zutil.ObjectUtil;
import zutil.log.LogUtil;
import zutil.net.http.HttpClient;
import zutil.net.http.HttpHeader;
import zutil.parser.DataNode;
import zutil.parser.json.JSONParser;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.logging.Logger;
/**
* A class that interfaces with the Tibber API.
*/
public class TibberAPIClient {
private static final Logger logger = LogUtil.getLogger();
private static final String TIBBER_API_ENDPOINT = "https://api.tibber.com/v1-beta/gql";
private static SimpleDateFormat DATE_PARSER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); // 2024-12-28T23:00:00.000+01:00
private String tibberToken;
/**
* Creates an instance of the TibberAPIClient.
*
* @param token is the authentication token required to connect to the API.
*/
public TibberAPIClient(String token) {
this.tibberToken = token;
}
/**
* Retrieves the consumption reported by Tibber.
*
* @return
*/
public TibberConsumption getConsumption() throws IOException {
String requestQuery = "{ " +
"\"query\": \"{" +
"viewer {" +
"homes {" +
"consumption(resolution: HOURLY, last: 1) {" +
"nodes {" +
"from " +
"to " +
"cost " + // Total cost
"unitPrice " + // Cost per Kwh
"unitPriceVAT " + // Cost per Kwh with taxes
"consumption " + // Total consumption
"consumptionUnit " + // Should be Kwh
"}" +
"}" +
"currentSubscription {" +
"priceInfo {" +
"current {" +
"total " +
"energy " +
"tax " +
"startsAt " +
"}" +
"}" +
"}" +
"}" +
"}" +
"}\"" +
"}";
DataNode responseRoot = sendRequest(requestQuery);
DataNode data = responseRoot.get("data").get("viewer").get("homes").get(0).get("consumption").get("nodes").get(0);
// Data example:
// unitPrice=0.1507875, cost=0.3131856375, from=2024-12-28T21:00:00.000+01:00, consumption=2.077, to=2024-12-28T22:00:00.000+01:00, unitPriceVAT=0.0301575, consumptionUnit=kWh
TibberConsumption consumption = new TibberConsumption();
try {
consumption.timestamp = DATE_PARSER.parse(data.getString("from")).getTime();
} catch (ParseException e) {
logger.warning("Was unable to parse timestamp from Tibber API.");
}
if (data.get("cost") != null) {
consumption.cost = data.getDouble("cost");
}
if (data.get("unitPrice") != null) {
consumption.unitPrice = data.getDouble("unitPrice");
}
if (data.get("unitPriceVAT") != null) {
consumption.unitPriceVAT = data.getDouble("unitPriceVAT");
}
if (data.get("consumption") != null) {
consumption.consumption = data.getDouble("consumption");
}
if (data.get("consumptionUnit") != null) {
consumption.consumptionUnit = data.getString("consumptionUnit");
}
return consumption;
}
private DataNode sendRequest(String query) throws IOException {
HttpClient client = new HttpClient(HttpClient.HttpRequestType.POST);
client.setURL(TIBBER_API_ENDPOINT);
client.setHeader("Authorization", "Bearer " + HalContext.getStringProperty(tibberToken));
client.setHeader("Content-Type", "application/json");
client.setContent(query);
logger.finest("Request: " + query);
HttpHeader header = client.send();
JSONParser parser = new JSONParser(header.getInputStream());
DataNode json = parser.read();
logger.finest("Received data from Tibber API: " + json);
if (header.getResponseStatusCode() != 200) {
throw new IOException("There was a error fetching data from tibber: StatusCode=" + header.getResponseStatusCode() + ", Response=" + header.getResponseStatusString());
}
if (!ObjectUtil.isEmpty(json.get("error"))) {
throw new IOException("There was a error fetching data from tibber: " + json.getString("error"));
}
return json;
}
public static class TibberConsumption {
/** The timestamp of when the data was reported */
public long timestamp;
/** Total cost */
public double cost;
/** Cost per Kwh */
public double unitPrice;
/** Cost per Kwh with taxes */
public double unitPriceVAT;
/** Total consumption */
public double consumption;
/** Consumption unit, should in general be Kwh */
public String consumptionUnit;
}
}

View file

@ -0,0 +1,136 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2024-2025 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.plugin.vendor.tibber;
import se.hal.HalContext;
import se.hal.HalServer;
import se.hal.intf.*;
import se.hal.plugin.vendor.tibber.device.TibberElectricityCostSensor;
import se.hal.plugin.vendor.tibber.device.TibberElectricityPriceSensor;
import se.hal.plugin.vendor.tibber.device.TibberPowerConsumptionSensor;
import se.hal.struct.devicedata.PriceSensorData;
import se.hal.util.ListenerUtil;
import zutil.log.LogUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TibberController implements HalSensorController, Runnable, HalDaemon, HalAutostartController {
private static final Logger logger = LogUtil.getLogger();
private static final String CONFIG_TIBBER_TOKEN = "hal_tibber.token";
private static final int POLL_TIME = 60*60; // poll every 1h defined in sec
private TibberAPIClient tibberClient;
private List<TibberDevice> registeredDevices = new ArrayList<>();
private List<HalDeviceReportListener> deviceListeners = new CopyOnWriteArrayList<>();
private ScheduledFuture<?> threadSchedule;
public TibberController() {}
@Override
public boolean isAvailable() {
return HalContext.containsProperty(CONFIG_TIBBER_TOKEN);
}
@Override
public void initialize() {
tibberClient = new TibberAPIClient(HalContext.getStringProperty(CONFIG_TIBBER_TOKEN));
HalServer.registerDaemon(this);
}
@Override
public void initiate(ScheduledExecutorService executor) {
threadSchedule = executor.scheduleAtFixedRate(this, 10, POLL_TIME, TimeUnit.SECONDS);
}
@Override
public synchronized void run() {
if (!isAvailable()) {
logger.warning("Controller not available yet.");
return;
}
try {
logger.fine("Querying Tibber API for new data.");
TibberAPIClient.TibberConsumption consumption = tibberClient.getConsumption();
if (consumption == null) {
logger.severe("There was a error fetching data from Tibber API");
return;
}
if (consumption.cost > 0) {
ListenerUtil.callReportReceived(deviceListeners, new TibberElectricityCostSensor(), new PriceSensorData(consumption.cost, consumption.timestamp));
}
if (consumption.unitPriceVAT > 0) {
ListenerUtil.callReportReceived(deviceListeners, new TibberElectricityPriceSensor(), new PriceSensorData(consumption.unitPriceVAT, consumption.timestamp));
}
if (consumption.consumption > 0) {
ListenerUtil.callReportReceived(deviceListeners, new TibberPowerConsumptionSensor(), new PriceSensorData(consumption.consumption, consumption.timestamp));
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Tibber API querying failed.", e);
}
}
@Override
public synchronized void register(HalDeviceConfig deviceConfig) {
if (deviceConfig instanceof TibberDevice)
registeredDevices.add((TibberDevice) deviceConfig);
}
@Override
public synchronized void deregister(HalDeviceConfig deviceConfig) {
registeredDevices.remove(deviceConfig);
}
@Override
public int size() {
return registeredDevices.size();
}
@Override
public void addListener(HalDeviceReportListener listener) {
if (!deviceListeners.contains(listener))
deviceListeners.add(listener);
}
@Override
public synchronized void close() {
registeredDevices.clear();
threadSchedule.cancel(false);
}
}

View file

@ -0,0 +1,28 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2024-2025 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.plugin.vendor.tibber;
public interface TibberDevice {
}

View file

@ -0,0 +1,64 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2024-2025 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.plugin.vendor.tibber.device;
import se.hal.intf.HalSensorConfig;
import se.hal.intf.HalSensorController;
import se.hal.intf.HalSensorData;
import se.hal.plugin.vendor.tibber.TibberController;
import se.hal.struct.devicedata.CostSensorData;
/**
* A sensor that calculate current electricity bil
*/
public class TibberElectricityCostSensor implements HalSensorConfig {
@Override
public long getDataInterval() {
return 60*60*1000; // 1 h
}
@Override
public AggregationMethod getAggregationMethod() {
return AggregationMethod.SUM;
}
@Override
public Class<? extends HalSensorController> getDeviceControllerClass() {
return TibberController.class;
}
@Override
public Class<? extends HalSensorData> getDeviceDataClass() {
return CostSensorData.class;
}
@Override
public boolean equals(Object obj) {
return obj instanceof TibberElectricityCostSensor;
}
}

View file

@ -0,0 +1,64 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2024-2025 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.plugin.vendor.tibber.device;
import se.hal.intf.HalSensorConfig;
import se.hal.intf.HalSensorController;
import se.hal.intf.HalSensorData;
import se.hal.plugin.vendor.tibber.TibberController;
import se.hal.struct.devicedata.PriceSensorData;
/**
* A sensor that shows the price of electricity at a specific time
*/
public class TibberElectricityPriceSensor implements HalSensorConfig {
@Override
public long getDataInterval() {
return 60*60*1000; // 1 h
}
@Override
public AggregationMethod getAggregationMethod() {
return AggregationMethod.AVERAGE;
}
@Override
public Class<? extends HalSensorController> getDeviceControllerClass() {
return TibberController.class;
}
@Override
public Class<? extends HalSensorData> getDeviceDataClass() {
return PriceSensorData.class;
}
@Override
public boolean equals(Object obj) {
return obj instanceof TibberElectricityPriceSensor;
}
}

View file

@ -0,0 +1,61 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2024-2025 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.plugin.vendor.tibber.device;
import se.hal.intf.HalSensorConfig;
import se.hal.intf.HalSensorController;
import se.hal.intf.HalSensorData;
import se.hal.struct.devicedata.PowerConsumptionSensorData;
import se.hal.plugin.vendor.tibber.TibberController;
public class TibberPowerConsumptionSensor implements HalSensorConfig {
@Override
public long getDataInterval() {
return 60*60 * 1000; // 1 min
}
@Override
public AggregationMethod getAggregationMethod() {
return AggregationMethod.AVERAGE;
}
@Override
public Class<? extends HalSensorController> getDeviceControllerClass() {
return TibberController.class;
}
@Override
public Class<? extends HalSensorData> getDeviceDataClass() {
return PowerConsumptionSensorData.class;
}
@Override
public boolean equals(Object obj) {
return obj instanceof TibberPowerConsumptionSensor;
}
}

View file

@ -0,0 +1,12 @@
{
"version": 0.1,
"name": "Hal-Vendor-Tibber",
"description": "Plugin that connects to the Tibber API.",
"interfaces": [
{"se.hal.intf.HalAutostartController": "se.hal.plugin.vendor.tibber.TibberController"},
{"se.hal.intf.HalSensorConfig": "se.hal.plugin.vendor.tibber.device.TibberElectricityCostSensor"},
{"se.hal.intf.HalSensorConfig": "se.hal.plugin.vendor.tibber.device.TibberElectricityPriceSensor"},
{"se.hal.intf.HalSensorConfig": "se.hal.plugin.vendor.tibber.device.TibberPowerConsumptionSensor"}
]
}