Exemplo n.º 1
0
 async def on_message(topic, msg, retain):
     if topic.endswith("/set") is False:
         if retain:
             pin = topic[topic.rfind("easyGPIO/") + 9:]
         else:
             # topic without /set ignored if not retained
             return False
     else:
         pin = topic[topic.rfind("easyGPIO/") + 9:-4]
     print("__gpio pin", pin, msg, retain)
     try:
         _p = Pin(pin)
     except Exception as e:
         await _log.asyncLog("pin {!r} does not exist: {!s}".format(pin, e))
         return False
     if msg != "":
         if msg in _mqtt.payload_on:
             value = 1
         elif msg in _mqtt.payload_off:
             value = 0
         else:
             try:
                 value = int(msg)
             except ValueError:
                 value = None
         if value is None:
             await _log.logAsync(
                 "error",
                 "pin {!r} got no supported value {!r}".format(pin, msg))
             return False
         Pin(pin, machine.Pin.OUT).value(value)
         return True
     else:
         return Pin(pin, machine.Pin.IN).value()
Exemplo n.º 2
0
 def __init__(self, s0, s1, s2, s3=None, mux=None, adc=None, return_voltages=False):
     """ It is possibile to initialize with:
         - pin numbers (or string on esp8266)
         - mux object and pin numbers (of mux pins)
         - Pin objects (either from machine or mux Pin objects [no mux object needed], or Arduino)
         :type return_voltages: bool, True returns voltages on .read() else raw adc value
         :type mux: Mux object if a multiplexer is used
         :type adc: ADC pin number (esp32) or None (esp8266) or Arduino ADC object or any ADC object
         Amux uses default return values of ADC in .read()
         s3 is optional, only needed if 16 pins are used, 8 pins possible with s0-s2.
         Amux can be read like a list: value=amux[2]
     """
     if mux:
         # MUX pin numbers, not pin objects
         self._s0 = s0
         self._s1 = s1
         self._s2 = s2
         self._s3 = s3
         self._mux = mux
     else:
         # Pin will take care of returning the correct object
         self._s0 = Pin(s0, machine.Pin.OUT)
         self._s1 = Pin(s1, machine.Pin.OUT)
         self._s2 = Pin(s2, machine.Pin.OUT)
         if s3:
             self._s3 = Pin(s3, machine.Pin.OUT)
     if s3:
         self.__size = 16
     else:
         self.__size = 8
     self._return_voltages = return_voltages
     self._adc = _ADC(
         adc)  # no matter what adc is, _ADC will return an object with the unified ADC API
Exemplo n.º 3
0
 def __init__(self, pin_trigger, pin_echo, timeout=30000, temp_sensor: ComponentSensor = None,
              precision: int = 2, offset: float = 0, sleeping_time: int = 20,
              iterations: int = 30, percentage_failed_readings_abort: float = 0.66,
              value_template=None, friendly_name=None, **kwargs):
     """
     HC-SR04 ultrasonic sensor.
     Be sure to connect it to 5V but use a voltage divider to connect the Echo pin to an ESP.
     :param pin_trigger: pin number/object of trigger pin
     :param pin_echo: pin number/object of echo pin
     :param timeout: reading timeout, corresponds to sensor limit range of 4m
     :param temp_sensor: temperature sensor object
     :param precision: int, precision of distance value published and returned
     :param offset: float, distance value offset, shouldn't be needed
     :param sleeping_time: int, sleeping time between reading iterations
     :param iterations: int, reading iterations per sensor reading
     :param percentage_failed_readings_abort: float, if a higher percentage of readings was bad, the reading will be aborted
     :param value_template: optional template can be used to measure the reverse distance (e.g. water level)
     :param friendly_name: friendly name for homeassistant gui by mqtt discovery, defaults to "Distance"
     """
     global _unit_index
     _unit_index += 1
     super().__init__(COMPONENT_NAME, __version__, _unit_index, logger=_log, **kwargs)
     self._tr = Pin(pin_trigger, mode=machine.Pin.OUT)
     self._tr.value(0)
     self._ec = Pin(pin_echo, mode=machine.Pin.IN)
     self._to = timeout
     self._sleep = sleeping_time
     self._iters = iterations
     self._pfr = percentage_failed_readings_abort
     if temp_sensor is not None:
         self.checkSensorType(temp_sensor, SENSOR_TEMPERATURE)
     self._temp: ComponentSensor = temp_sensor
     self._addSensorType("distance", precision, offset, value_template or VALUE_TEMPLATE_FLOAT,
                         "cm", friendly_name, discovery_type=DISCOVERY_DISTANCE)
Exemplo n.º 4
0
 def __init__(self, r1, ra, adc, power_pin, ground_pin, ppm_conversion, temp_coef, k,
              temp_sensor, precision_ec=3, interval=None, topic_ec=None, topic_ppm=None,
              friendly_name_ec=None, friendly_name_ppm=None):
     # This makes it possible to use multiple instances of MySensor
     global _unit_index
     _unit_index += 1
     super().__init__(COMPONENT_NAME, __version__, _unit_index)
     self._interval = interval or config.INTERVAL_SENSOR_PUBLISH
     self._prec_ec = int(precision_ec)
     self._adc = ADC(adc)
     self._ppin = Pin(power_pin, machine.Pin.OUT)
     self._gpin = Pin(ground_pin, machine.Pin.IN)  # changing to OUTPUT GND when needed
     self._r1 = r1
     self._ra = ra
     self._ppm_conversion = ppm_conversion
     self._temp_coef = temp_coef
     self._k = k
     self._temp = temp_sensor
     if hasattr(temp_sensor, "temperature") is False:
         raise AttributeError(
             "Temperature sensor {!s}, type {!s} has no async method temperature()".format(
                 temp_sensor,
                 type(temp_sensor)))
     gc.collect()
     self._ec25 = None
     self._ppm = None
     self._time = 0
     self._topic_ec = topic_ec or _mqtt.getDeviceTopic("{!s}/{!s}".format("EC", self._count))
     self._topic_ppm = topic_ppm or _mqtt.getDeviceTopic("{!s}/{!s}".format("PPM", self._count))
     self._frn_ec = friendly_name_ec
     self._frn_ppm = friendly_name_ppm
Exemplo n.º 5
0
 def __init__(self,
              pin_trigger,
              pin_echo,
              timeout=30000,
              temp_sensor: ComponentSensor = None,
              precision=2,
              offset=0,
              interval_publish=None,
              interval_reading=None,
              mqtt_topic=None,
              value_template=None,
              friendly_name=None,
              discover=True,
              expose_intervals=False,
              intervals_topic=None):
     """
     HC-SR04 ultrasonic sensor.
     Be sure to connect it to 5V but use a voltage divider to connect the Echo pin to an ESP.
     :param pin_trigger: pin number/object of trigger pin
     :param pin_echo: pin number/object of echo pin
     :param timeout: reading timeout, corresponds to sensor limit range of 4m
     :param temp_sensor: temperature sensor object
     :param precision: int, precision of distance value published and returned
     :param offset: float, distance value offset, shouldn't be needed
     :param interval_publish: seconds, set to interval_reading to publish every reading. -1 for not publishing.
     :param interval_reading: seconds, set to -1 for not reading/publishing periodically. >0 possible for reading, 0 not allowed for reading..
     :param mqtt_topic: distance mqtt topic
     :param value_template: optional template can be used to measure the reverse distance (e.g. water level)
     :param friendly_name: friendly name for homeassistant gui by mqtt discovery, defaults to "Distance"
     :param discover: boolean, if the device should publish its discovery
     :param expose_intervals: Expose intervals to mqtt so they can be changed remotely
     :param intervals_topic: if expose_intervals then use this topic to change intervals.
     Defaults to <home>/<device-id>/<COMPONENT_NAME><_unit_index>/interval/set
     Send a dictionary with keys "reading" and/or "publish" to change either/both intervals.
     """
     global _unit_index
     _unit_index += 1
     super().__init__(COMPONENT_NAME, __version__, _unit_index, discover,
                      interval_publish, interval_reading, mqtt_topic, _log,
                      expose_intervals, intervals_topic)
     self._tr = Pin(pin_trigger, mode=machine.Pin.OUT)
     self._tr.value(0)
     self._ec = Pin(pin_echo, mode=machine.Pin.IN)
     self._to = timeout
     self.checkSensorType(temp_sensor, SENSOR_TEMPERATURE)
     self._temp: ComponentSensor = temp_sensor
     self._addSensorType("distance",
                         precision,
                         offset,
                         value_template or VALUE_TEMPLATE_FLOAT,
                         "cm",
                         friendly_name,
                         discovery_type=DISCOVERY_DISTANCE)
Exemplo n.º 6
0
 async def _loop(self):
     if self._PIN_BELL_IRQ_DIRECTION == machine.Pin.IRQ_FALLING:
         self._pin_bell = Pin(self._pin_bell, machine.Pin.IN, machine.Pin.PULL_UP)
     else:
         self._pin_bell = Pin(self._pin_bell, machine.Pin.IN)
     self._event_bell = Event()
     self._timer_lock = Lock()
     self._pin_bell.irq(trigger=self._PIN_BELL_IRQ_DIRECTION, handler=self.__irqBell)
     self._event_bell.clear()
     asyncio.get_event_loop().create_task(self.__bell())
     self._timer_bell = machine.Timer(1)
     await _log.asyncLog("info", "Bell initialized")
     gc.collect()
Exemplo n.º 7
0
    def __init__(self,
                 r1,
                 ra,
                 rg,
                 adc,
                 power_pin,
                 ground_pin,
                 ppm_conversion,
                 temp_coef,
                 k,
                 temp_sensor: ComponentSensor,
                 read_timeout=400,
                 iterations=1,
                 precision_ec=3,
                 friendly_name_ec=None,
                 friendly_name_ppm=None,
                 **kwargs):
        # This makes it possible to use multiple instances of MySensor
        global _unit_index
        _unit_index += 1
        self.checkSensorType(temp_sensor, SENSOR_TEMPERATURE)
        super().__init__(COMPONENT_NAME,
                         __version__,
                         _unit_index,
                         logger=_log,
                         **kwargs)
        self._temp = temp_sensor
        self._addSensorType("ec", precision_ec, 0,
                            VALUE_TEMPLATE_JSON.format("ec|float"), "mS",
                            friendly_name_ec or "EC", self._topic,
                            DISCOVERY_EC)
        self._addSensorType("ppm", 0, 0, VALUE_TEMPLATE_JSON.format("ppm|int"),
                            "ppm", friendly_name_ppm or "PPM", self._topic,
                            DISCOVERY_PPM)

        self._adc = ADC(adc)
        self._ppin = Pin(power_pin,
                         machine.Pin.IN)  # changing to OUTPUT GND when needed
        self._gpin = Pin(ground_pin,
                         machine.Pin.IN)  # changing to OUTPUT GND when needed
        self._r1 = r1
        self._ra = ra
        self._rg = rg
        self._ppm_conversion = ppm_conversion
        self._temp_coef = temp_coef
        self._k = k
        self._to = read_timeout
        self._iters = iterations
        gc.collect()
Exemplo n.º 8
0
 def __init__(self, pin, debounce_time, on_time=None, direction=None, pull_up=True,
              friendly_name=None, friendly_name_last=None, confirmations=1,
              ac_signal=False, **kwargs):
     global _unit_index
     _unit_index += 1
     super().__init__(COMPONENT_NAME, __version__, _unit_index, logger=_log,
                      interval_reading=0.001, interval_publish=0.001, expose_intervals=False,
                      **kwargs)
     self._low_active = True if direction == 2 else False
     self._debounce_time = debounce_time
     self._on_time = on_time or 500
     self._pin_bell = Pin(pin, machine.Pin.IN, machine.Pin.PULL_UP if pull_up else None)
     self._timer_delay = 0
     self._last_activation = 0
     self._confirmations = confirmations
     self._ac = ac_signal
     self._active = False
     gc.collect()
     self._addSensorType("bell", friendly_name=friendly_name, binary_sensor=True,
                         discovery_type=_DISCOVERY_BELL, retained_publication=True,
                         topic=_mqtt.getDeviceTopic("bell{!s}".format(self._count)))
     self._addSensorType("last_bell", friendly_name=friendly_name_last,
                         topic=_mqtt.getDeviceTopic("last_bell{!s}".format(self._count)),
                         discovery_type=DISCOVERY_TIMELAPSE, retained_publication=True)
     _log.info("Bell initialized")
     gc.collect()
Exemplo n.º 9
0
    def __init__(
            self,
            pin,
            precision_temp=2,
            precision_humid=1,  # extend or shrink according to your sensor
            offset_temp=0,
            offset_humid=0,  # also here
            interval=None,
            mqtt_topic=None,
            friendly_name=None):
        super().__init__()
        self._interval = interval or config.INTERVAL_SEND_SENSOR
        self._topic = mqtt_topic or _mqtt.getDeviceTopic(_component_name)

        ##############################
        # adapt to your sensor by extending/removing unneeded values like in the constructor arguments
        self._prec_temp = int(precision_temp)
        self._prec_humid = int(precision_humid)
        ###
        self._offs_temp = float(offset_temp)
        self._offs_humid = float(offset_humid)
        ##############################
        # create sensor object
        self.sensor = Sensor(
            Pin(pin))  # add neccessary constructor arguments here
        ##############################
        global _count
        self._count = _count
        _count += 1
        self._frn = friendly_name
        gc.collect()
Exemplo n.º 10
0
 def __init__(self,
              pin,
              precision_temp=2,
              precision_humid=1,
              offset_temp=0,
              offset_humid=0,
              friendly_name_temp=None,
              friendly_name_humid=None,
              **kwargs):
     # This makes it possible to use multiple instances of MySensor and have unique identifier
     global _unit_index
     _unit_index += 1
     super().__init__(COMPONENT_NAME,
                      __version__,
                      _unit_index,
                      logger=_log,
                      **kwargs)
     self._addSensorType(SENSOR_TEMPERATURE, precision_temp, offset_temp,
                         _VAL_T_TEMPERATURE, "°C", friendly_name_temp)
     self._addSensorType(SENSOR_HUMIDITY, precision_humid, offset_humid,
                         _VAL_T_HUMIDITY, "%", friendly_name_humid)
     ##############################
     # create sensor object
     self.sensor = Sensor(
         Pin(pin))  # add neccessary constructor arguments here
     ##############################
     gc.collect()
Exemplo n.º 11
0
 def __init__(self,
              adc,
              voltage_max,
              voltage_min,
              multiplier_adc,
              cutoff_pin=None,
              precision_voltage=2,
              interval_watching=1,
              interval=None,
              mqtt_topic=None,
              friendly_name=None,
              friendly_name_abs=None):
     super().__init__()
     self._interval = interval or config.INTERVAL_SEND_SENSOR
     self._interval_watching = interval_watching
     self._topic = mqtt_topic or _mqtt.getDeviceTopic(_component_name)
     self._precision = int(precision_voltage)
     self._adc = ADC(adc)  # unified ADC interface
     self._voltage_max = voltage_max
     self._voltage_min = voltage_min
     self._multiplier = multiplier_adc
     self._cutoff_pin = None if cutoff_pin is None else (Pin(
         cutoff_pin, machine.Pin.OUT))
     if self._cutoff_pin is not None:
         self._cutoff_pin.value(0)
     self._frn = friendly_name
     self._frn_abs = friendly_name_abs
     gc.collect()
     self._event_low = None
     self._event_high = None
Exemplo n.º 12
0
 def __init__(self,
              pin,
              precision_temp=2,
              precision_humid=1,
              offset_temp=0,
              offset_humid=0,
              interval_publish=None,
              interval_reading=None,
              mqtt_topic=None,
              friendly_name_temp=None,
              friendly_name_humid=None,
              discover=True,
              expose_intervals=False,
              intervals_topic=None):
     # This makes it possible to use multiple instances of MySensor and have unique identifier
     global _unit_index
     _unit_index += 1
     super().__init__(COMPONENT_NAME, __version__, _unit_index, discover,
                      interval_publish, interval_reading, mqtt_topic, _log,
                      expose_intervals, intervals_topic)
     self._addSensorType(SENSOR_TEMPERATURE, precision_temp, offset_temp,
                         _VAL_T_TEMPERATURE, "°C", friendly_name_temp)
     self._addSensorType(SENSOR_HUMIDITY, precision_humid, offset_humid,
                         _VAL_T_HUMIDITY, "%", friendly_name_humid)
     ##############################
     # create sensor object
     self.sensor = Sensor(
         Pin(pin))  # add neccessary constructor arguments here
     ##############################
     gc.collect()
Exemplo n.º 13
0
 def __init__(self,
              pin,
              rom: str = None,
              auto_detect=False,
              precision_temp: int = 2,
              offset_temp: float = 0,
              friendly_name=None,
              **kwargs):
     """
     Class for a single ds18 unit to provide an interface to a single unit.
     Alternatively it can be used to automatically detect all connected units
     and create objects for those units.
     :param pin: pin number/name/object
     :param rom: optional, ROM of the specific DS18 unit, can be string or bytearray
     (in json bytearray not possible). If not given then the first found ds18 unit will be used,
     no matter the ROM. Makes it possible to have a generic ds18 unit.
     :param auto_detect: optional, if true and ROM is None then all connected ds18 units will automatically generate a sensor object with the given options.
     :param precision_temp: the precision to for returning/publishing values
     :param offset_temp: temperature offset to adjust bad sensor readings
     :param friendly_name: friendly name in homeassistant. Has no effect if rom is None and auto_detect True
     """
     if rom is None and auto_detect:
         # only a dummy sensor for detecting connected sensors
         interval_reading = kwargs[
             "interval_reading"] if "interval_reading" in kwargs else None
         interval_publish = kwargs[
             "interval_publish"] if "interval_publish" in kwargs else None
         self._instances = {}  # rom:object
         self._auto_detect = True
         self._kwargs = kwargs  # store kwargs for initialization of detected sensors
         kwargs[
             "interval_reading"] = 60  # scan every 60 seconds for new units
         kwargs["interval_publish"] = -1
     global _unit_index
     _unit_index += 1
     super().__init__(COMPONENT_NAME,
                      __version__,
                      _unit_index,
                      logger=_log,
                      **kwargs)
     self.rom: str = rom
     self._generic = True if rom is None and not auto_detect else False
     if type(pin) == ds18x20.DS18X20:
         self.sensor: ds18x20.DS18X20 = pin
     else:
         self._pins[pin] = ds18x20.DS18X20(onewire.OneWire(Pin(pin)))
         self.sensor: ds18x20.DS18X20 = self._pins[pin]
         self._last_conv[self.sensor] = None
     if rom or not auto_detect:  # sensor with rom or generic sensor
         self._addSensorType(SENSOR_TEMPERATURE, precision_temp,
                             offset_temp, VALUE_TEMPLATE_FLOAT, "°C",
                             friendly_name)
         self._auto_detect = False
     elif self._auto_detect:
         self._kwargs["interval_reading"] = interval_reading
         self._kwargs["interval_publish"] = interval_publish
         self._kwargs["precision_temp"] = precision_temp
         self._kwargs["offset_temp"] = offset_temp
     gc.collect()
Exemplo n.º 14
0
 def __init__(self, pin, mqtt_topic=None, friendly_name=None):
     super().__init__()
     mqtt_topic = mqtt_topic or _mqtt.getDeviceTopic(
         "{!s}/{!s}".format(_component_name, str(pin)), is_request=True)
     self._topic = mqtt_topic
     self._subscribe(self._topic, self.on_message)
     self.pin = Pin(pin, machine.Pin.OUT, value=0)
     self._frn = friendly_name
     self._name = "{!s}_{!s}".format(_component_name, pin)
Exemplo n.º 15
0
async def pin(HEATER, PIN, INVERTED=False):
    global _pin
    global _inverted
    _inverted = INVERTED
    _pin = Pin(PIN, machine.Pin.OUT)
    await log.asyncLog("info",
                       "Heater hardware PIN version {!s}".format(__version__))
    HEATER.registerHardware(_setHeaterPower)
    await _setHeaterPower(0)  # initialize heater as shut down
Exemplo n.º 16
0
 def __init__(self, pin, active_high=True):
     super().__init__(COMPONENT_NAME,
                      __version__,
                      discover=False,
                      unit_index=0)
     self.pin = Pin(pin, machine.Pin.OUT, value=0 if active_high else 1)
     self._active_high = active_high
     self._next = []
     asyncio.get_event_loop().create_task(self._loop())
Exemplo n.º 17
0
 def __init__(self,
              adc_pin,
              water_voltage,
              air_voltage,
              sensor_types,
              power_pin=None,
              power_warmup=None,
              publish_converted_value=False,
              mqtt_topic=None,
              interval=None,
              friendly_name=None,
              friendly_name_cv=None,
              discover=True):
     super().__init__(COMPONENT_NAME, __version__, discover)
     self._adc = ADC(adc_pin)
     if power_pin is None:
         self._ppin = None
     else:
         if type(power_pin) == list:
             self._ppin = []
             for pin in power_pin:
                 self._ppin.append(Pin(pin, machine.Pin.OUT))
         else:
             self._ppin = Pin(power_pin, machine.Pin.OUT)
     self._power_warmup = power_warmup or None if power_pin is None else 10
     self._sensor_types = sensor_types
     if isinstance(
             self._adc, pyADC
     ):  # pyADC provides unified single ADC interface, not AMUX
         raise TypeError("Single ADC (no Amux) can't have multiple sensors")
     self._water_v = water_voltage
     self._air_v = air_voltage
     if type(sensor_types) == list:
         if type(water_voltage) != list or type(air_voltage) != list:
             raise TypeError(
                 "Voltages have to be lists with multiple sensor_types")
     self._pub_cv = publish_converted_value
     self._topic = mqtt_topic
     self._interval = interval or config.INTERVAL_SENSOR_PUBLISH
     self._lock = Lock()
     self._frn = friendly_name
     self._frn_cv = friendly_name_cv
     gc.collect()
     asyncio.get_event_loop().create_task(self._loop())
Exemplo n.º 18
0
 def __init__(self, pin, on_time=50, off_time=50, iters=20, **kwargs):
     self.pin = Pin(pin, machine.Pin.OUT, value=0)
     self.on_time = on_time
     self.off_time = off_time
     self.iters = iters
     # This makes it possible to use multiple instances of LED
     global _unit_index
     _unit_index += 1
     super().__init__(COMPONENT_NAME, __version__, _unit_index, **kwargs)
     gc.collect()
Exemplo n.º 19
0
 def __init__(self,
              pin,
              pull=None,
              pressed_component=None,
              pressed_method="on",
              released_component=None,
              released_method="off",
              double_pressed_component=None,
              double_pressed_method="on",
              long_pressed_component=None,
              long_pressed_method="on",
              suppress=False):
     """
     :param pin: pin number or name
     :param pull: None for no pullup or pull_down, otherwise value of pull configuration
     :param pressed_component: component name of component to be turned on when button pressed
     :param pressed_method: string of the method of the component that is to be called
     :param released_component: component name of component to be turned on when button released
     :param released_method: string of the method of the component that is to be called
     :param double_pressed_component: component name of component to be turned on when button double pressed
     :param double_pressed_method: string of the method of the component that is to be called
     :param long_pressed_component: component name of component to be turned on when button long pressed
     :param long_pressed_method: string of the method of the component that is to be called
     :param suppress: suppress calling release function after double click and long press. Will delay release function by 300ms if double click is used.
     """
     for comp in (pressed_component, released_component,
                  long_pressed_component):
         if type(comp) == str and comp not in loaded_components:
             raise TypeError(
                 "Component {!s} could not be found".format(comp))
     if type(pressed_component) == str:
         pressed_component = loaded_components[pressed_component]
     if type(released_component) == str:
         released_component = loaded_components[released_component]
     if type(double_pressed_component) == str:
         double_pressed_component = loaded_components[
             double_pressed_component]
     if type(long_pressed_component) == str:
         long_pressed_component = loaded_components[long_pressed_component]
     pin = Pin(pin, machine.Pin.IN, pull)
     Pushbutton.__init__(self, pin, suppress=suppress)
     global _unit_index
     _unit_index += 1
     Component.__init__(self, COMPONENT_NAME, __version__, _unit_index)
     if pressed_component is not None:
         self.press_func(getattr(pressed_component, pressed_method))
     if released_component is not None:
         self.release_func(getattr(released_component, released_method))
     if double_pressed_component is not None:
         self.double_func(
             getattr(double_pressed_component, double_pressed_method))
     if long_pressed_component is not None:
         self.long_func(getattr(long_pressed_component,
                                long_pressed_method))
Exemplo n.º 20
0
 def __init__(self, pin, on_time=50, off_time=50, iters=20, mqtt_topic=None,
              friendly_name=None, discover=True):
     self.pin = Pin(pin, machine.Pin.OUT, value=0)
     self.on_time = on_time
     self.off_time = off_time
     self.iters = iters
     # This makes it possible to use multiple instances of LED
     global _unit_index
     _unit_index += 1
     super().__init__(COMPONENT_NAME, __version__, _unit_index, mqtt_topic, discover=discover)
     self._frn = friendly_name
     gc.collect()
Exemplo n.º 21
0
 def __init__(self, adc, power_pin=None, cutoff_voltage=None, interval_publish=None,
              interval_reading=1, mqtt_topic=None, friendly_name=None, discover=True,
              expose_intervals=False, intervals_topic=None):
     interval_publish = interval_publish or -1
     global _unit_index
     _unit_index += 1
     super().__init__(COMPONENT_NAME, __version__, _unit_index, discover, interval_publish,
                      interval_reading, mqtt_topic, _log, expose_intervals, intervals_topic)
     self._adc = ADC(adc)
     self._ppin = Pin(power_pin, machine.Pin.OUT) if power_pin is not None else None
     self._cv = cutoff_voltage or self._adc.maxVoltage()
     self._lv = None
     self._addSensorType(SENSOR_BINARY_MOISTURE, 0, 0, VALUE_TEMPLATE, "", friendly_name,
                         mqtt_topic, None, True)
     self._pub_coro = None
Exemplo n.º 22
0
 def __init__(self, pin, interval=None, auto_discovery=False):
     """
     The DS18 onewire controller. Reads all connected (and configured) units.
     :param pin: Pin object or integer or name
     :param interval: how often the sensors are read and published
     :param auto_discovery: if True then one object for each found DS18 unit will be created. This is only useful if
     the Units are not going to be used in other components and only the read temperature is interesting.
     """
     self._interval = interval or config.INTERVAL_SEND_SENSOR
     ds18x20.DS18X20.__init__(self, onewire.OneWire(Pin(pin)))
     gc.collect()
     self._lock = config.Lock()
     global _ds18_controller
     _ds18_controller = self
     asyncio.get_event_loop().create_task(self._loop(auto_discovery))
Exemplo n.º 23
0
 def __init__(self, pin_trigger, pin_echo, timeout=30000, temp_sensor=None,
              precision=2, offset=0,
              interval=None, mqtt_topic=None,
              mqtt_topic_interval=None, value_template=None, friendly_name=None):
     """
     HC-SR04 ultrasonic sensor.
     Be sure to connect it to 5V but use a voltage divider to connect the Echo pin to an ESP.
     :param pin_trigger: pin number/object of trigger pin
     :param pin_echo: pin number/object of echo pin
     :param timeout: reading timeout, corresponds to sensor limit range of 4m
     :param temp_sensor: temperature sensor object
     :param precision: int, precision of distance value published and returned
     :param offset: float, distance value offset, shouldn't be needed
     :param interval: float, interval in which the distance value gets measured and published
     :param mqtt_topic: distance mqtt topic
     :param mqtt_topic_interval: interval mqtt topic for changing the reading interval
     :param value_template: optional template can be used to measure the reverse distance (e.g. water level)
     :param friendly_name: friendly name for homeassistant gui by mqtt discovery, defaults to "Distance"
     """
     super().__init__()
     self._frn = friendly_name
     self._valt = value_template
     self._tr = Pin(pin_trigger, mode=machine.Pin.OUT)
     self._tr.value(0)
     self._ec = Pin(pin_echo, mode=machine.Pin.IN)
     self._to = timeout
     self._temp = temp_sensor
     self._pr = int(precision)
     self._off = float(offset)
     self._topic = mqtt_topic or _mqtt.getDeviceTopic("hcsr04")
     self._topic_int = mqtt_topic_interval or _mqtt.getDeviceTopic("hcsr04/interval", is_request=True)
     self.interval = interval or config.INTERVAL_SEND_SENSOR  # can be changed anytime
     global _count
     self._count = _count
     _count += 1
     self._subscribe(self._topic_int, self._changeInterval)
Exemplo n.º 24
0
 def __init__(self, adc, power_pin=None, cutoff_voltage=None, interval=None,
              interval_reading=1, topic=None, friendly_name=None):
     super().__init__()
     self._ir = interval_reading
     self._adc = ADC(adc)
     self._ppin = Pin(power_pin, machine.Pin.OUT) if power_pin is not None else None
     self._cv = cutoff_voltage or self._adc.maxVoltage()
     global _instances
     _instances.append(self)
     global _count
     self._t = topic or _mqtt.getDeviceTopic("waterSensor/{!s}".format(_count))
     self._count = _count
     _count += 1
     self._lv = None
     self._tm = time.ticks_ms()
     interval = interval or config.INTERVAL_SEND_SENSOR
     self._int = interval * 1000
     self._frn = friendly_name
Exemplo n.º 25
0
    def __init__(self,
                 pin,
                 file: str,
                 name_on: str,
                 name_off: str,
                 reps: int = 5,
                 **kwargs):
        global _unit_index
        _unit_index += 1
        global _tx
        if file not in _remotes and _tx is None:
            pin = Pin(pin, machine.Pin.OUT)
            _tx = TX(pin, file, reps)
            _remotes[file] = _tx._data
        elif file not in _remotes:
            with open(file, 'r') as f:
                rem = json.load(f)
            # exceptions are forwarded to the caller
            _remotes[file] = rem
        if name_on not in _remotes[file]:
            raise AttributeError("name_on {!r} not in file {!s}".format(
                name_on, file))
        if name_off not in _remotes[file]:
            raise AttributeError("name_off {!r} not in file {!s}".format(
                name_off, file))

        super().__init__(COMPONENT_NAME,
                         __version__,
                         _unit_index,
                         wait_for_lock=True,
                         initial_state=None,
                         **kwargs)
        # Unknown initial state. Should be sorted by retained state topic

        self._reps = reps
        self._file = file
        self._len_on = int(sum(_remotes[self._file][name_on]) * 1.1 / 1000)
        self._len_off = int(sum(_remotes[self._file][name_off]) * 1.1 / 1000)
        self._name_on = name_on
        self._name_off = name_off

        # one lock for all switches, overrides lock created by the base class
        self._lock = _lock
Exemplo n.º 26
0
 def __init__(self,
              pin,
              active_high=True,
              mqtt_topic=None,
              instance_name=None,
              **kwargs):
     mqtt_topic = mqtt_topic or _mqtt.getDeviceTopic(
         "{!s}/{!s}".format(COMPONENT_NAME, str(pin)), is_request=True)
     global _unit_index
     _unit_index += 1
     super().__init__(COMPONENT_NAME,
                      __version__,
                      _unit_index,
                      mqtt_topic=mqtt_topic,
                      instance_name=instance_name
                      or "{!s}_{!s}".format(COMPONENT_NAME, pin),
                      **kwargs)
     self.pin = Pin(pin, machine.Pin.OUT, value=0 if active_high else 1)
     self._state = not active_high
     self._active_high = active_high
Exemplo n.º 27
0
 def __init__(self,
              pin,
              on_time=50,
              off_time=50,
              iters=20,
              mqtt_topic=None,
              friendly_name=None):
     super().__init__()
     self.pin = Pin(pin, machine.Pin.OUT, value=0)
     self.on_time = on_time
     self.off_time = off_time
     self.iters = iters
     self.lock = config.Lock()
     # This makes it possible to use multiple instances of LED
     global _count
     self._count = _count
     _count += 1
     mqtt_topic = mqtt_topic or _mqtt.getDeviceTopic(
         "{!s}{!s}".format(_component_name, self._count), is_request=True)
     self._topic = mqtt_topic
     self._frn = friendly_name
     gc.collect()
Exemplo n.º 28
0
 def __init__(self, adc, voltage_max: float, voltage_min: float, multiplier_adc: float,
              cutoff_pin=None, precision_voltage: int = 2, interval_reading: float = 1,
              interval_publish: float = None, mqtt_topic: str = None, friendly_name: str = None,
              friendly_name_abs: str = None, discover: bool = True,
              expose_intervals: bool = False, intervals_topic: str = None):
     global _unit_index
     _unit_index += 1
     super().__init__(COMPONENT_NAME, __version__, _unit_index, discover, interval_publish,
                      interval_reading, mqtt_topic, _log, expose_intervals, intervals_topic)
     self._adc = ADC(adc)  # unified ADC interface
     self._voltage_max = voltage_max
     self._voltage_min = voltage_min
     self._multiplier = multiplier_adc
     self._cutoff_pin = None if cutoff_pin is None else (Pin(cutoff_pin, machine.Pin.OUT))
     if self._cutoff_pin is not None:
         self._cutoff_pin.value(0)
     self._event_low = None
     self._event_high = None
     self._addSensorType(SENSOR_BATTERY, 2, 0, _VAL_T_CHARGE, "%", friendly_name_abs)
     self._addSensorType("voltage", precision_voltage, 0, _VAL_T_VOLTAGE, "V", friendly_name,
                         None, _TYPE_VOLTAGE)
     asyncio.get_event_loop().create_task(self._events())
     gc.collect()
Exemplo n.º 29
0
 def __init__(self,
              pin,
              on_object=None,
              on_function=None,
              mqtt_topic=None,
              off_object=None,
              off_function=None,
              publish_mqtt=True,
              debounce_ms=None):
     super().__init__(Pin(pin, machine.Pin.PULL_UP))
     if debounce_ms is not None:
         self.debounce_ms = debounce_ms
     # if both func are None, status will still be published if publish_mqtt=True
     mqtt_topic = mqtt_topic or (_mqtt.getDeviceTopic("Switch")
                                 if publish_mqtt else None)
     on_func = _checkFunction(on_object, on_function)
     self.close_func(wrapAction, (on_func, mqtt_topic, "ON"))
     gc.collect()
     off_func = _checkFunction(off_object, off_function)
     if off_func is not None:
         self.open_func(wrapAction, (off_func, mqtt_topic, "OFF"))
     else:
         self.open_func(wrapAction, (on_func, mqtt_topic, "OFF"))
     gc.collect()
Exemplo n.º 30
0
 def __init__(self,
              adc,
              power_pin=None,
              cutoff_voltage=None,
              interval_reading=1,
              friendly_name=None,
              **kwargs):
     global _unit_index
     _unit_index += 1
     super().__init__(COMPONENT_NAME,
                      __version__,
                      _unit_index,
                      logger=_log,
                      interval_reading=interval_reading,
                      interval_publish=-1,
                      **kwargs)
     self._adc = ADC(adc)
     self._ppin = Pin(power_pin,
                      machine.Pin.OUT) if power_pin is not None else None
     self._cv = cutoff_voltage or self._adc.maxVoltage()
     self._lv = None
     self._addSensorType(SENSOR_BINARY_MOISTURE, 0, 0, VALUE_TEMPLATE, "",
                         friendly_name, self._topic, None, True)
     self._pub_task = None