]> git.basschouten.com Git - openhab-addons.git/blob
f658fc9985283a3f1a606a93964066ecd58cd329
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.mqtt.homeassistant.internal;
14
15 import java.util.regex.Pattern;
16
17 import org.apache.commons.lang.StringUtils;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.openhab.binding.mqtt.generic.values.NumberValue;
21 import org.openhab.binding.mqtt.generic.values.TextValue;
22 import org.openhab.binding.mqtt.generic.values.Value;
23
24 /**
25  * A MQTT sensor, following the https://www.home-assistant.io/components/sensor.mqtt/ specification.
26  *
27  * @author David Graeff - Initial contribution
28  */
29 @NonNullByDefault
30 public class ComponentSensor extends AbstractComponent<ComponentSensor.ChannelConfiguration> {
31     public static final String sensorChannelID = "sensor"; // Randomly chosen channel "ID"
32     private static final Pattern triggerIcons = Pattern.compile("^mdi:(toggle|gesture).*$");
33
34     /**
35      * Configuration class for MQTT component
36      */
37     static class ChannelConfiguration extends BaseChannelConfiguration {
38         ChannelConfiguration() {
39             super("MQTT Sensor");
40         }
41
42         protected @Nullable String unit_of_measurement;
43         protected @Nullable String device_class;
44         protected boolean force_update = false;
45         protected int expire_after = 0;
46
47         protected String state_topic = "";
48     }
49
50     public ComponentSensor(CFactory.ComponentConfiguration componentConfiguration) {
51         super(componentConfiguration, ChannelConfiguration.class);
52
53         if (channelConfiguration.force_update) {
54             throw new UnsupportedOperationException("Component:Sensor does not support forced updates");
55         }
56
57         Value value;
58
59         String uom = channelConfiguration.unit_of_measurement;
60
61         if (uom != null && StringUtils.isNotBlank(uom)) {
62             value = new NumberValue(null, null, null, uom);
63         } else {
64             value = new TextValue();
65         }
66
67         String icon = channelConfiguration.icon;
68
69         boolean trigger = triggerIcons.matcher(icon).matches();
70
71         buildChannel(sensorChannelID, value, channelConfiguration.name, componentConfiguration.getUpdateListener())//
72                 .stateTopic(channelConfiguration.state_topic, channelConfiguration.value_template)//
73                 .trigger(trigger).build();
74     }
75 }