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)
class GPIO(ComponentSwitch): 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 async def _on(self): self.pin.value(1 if self._active_high else 0) return True async def _off(self): self.pin.value(0 if self._active_high else 1) return True
def __init__(self, shift_pin, store_pin, data_pin, number_multiplexer=1): self.shcp = PyPin(shift_pin, machine.Pin.OUT) self.stcp = PyPin(store_pin, machine.Pin.OUT) self.ds = PyPin(data_pin, machine.Pin.OUT) self.__data = bytearray(8 * number_multiplexer) self.__size = number_multiplexer self.write()
class GPIO(Component): 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) async def _discovery(self): await self._publishDiscovery(_component_type, self._topic[:-4], self._name, DISCOVERY_SWITCH, self._frn) async def on_message(self, topic, msg, retained): _log = logging.getLogger("gpio") if msg in _mqtt.payload_on: self.pin.value(1) return True elif msg in _mqtt.payload_off: self.pin.value(0) return True else: _log.error("Unknown payload {!r}, GPIO {!s}".format(msg, self.pin)) return False
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()
def __init__(self, r1, ra, adc, power_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): super().__init__() self._interval = interval or config.INTERVAL_SEND_SENSOR self._prec_ec = int(precision_ec) self._adc = ADC(adc) self._ppin = Pin(power_pin, machine.Pin.OUT) 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 # This makes it possible to use multiple instances of MySensor global _count self._count = _count _count += 1 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
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()
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)
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())
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()
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()
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)
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()
class LEDNotification(Component): 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() async def _init(self): await super()._init() self._subscribe(self._topic, self.on_message) await _mqtt.subscribe(self._topic, check_retained_state_topic=False) # not checking retained state as led only activates single-shot and default state is always off async def on_message(self, topic, msg, retain): if self.lock.locked(): return False async with self.lock: if msg in _mqtt.payload_on: _mqtt.schedulePublish(self._topic[:-4], "ON", qos=1) for i in range(0, self.iters): self.pin.value(1) await asyncio.sleep_ms(self.on_time) self.pin.value(0) await asyncio.sleep_ms(self.off_time) await _mqtt.publish(self._topic[:-4], "OFF", qos=1, retain=True) return False # will not publish the state "ON" to mqtt async def _discovery(self): name = "{!s}{!s}".format(_component_name, self._count) await self._publishDiscovery(_component_type, self._topic[:-4], name, DISCOVERY_SWITCH, self._frn)
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
def __init__(self, s0, s1, s2, pin, s3=None, mux=None, pin_direction="OUT", pin_pull=None): """ 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]) :type mux: Mux object if a multiplexer is used :type pin: pin number or string (esp8266) :type pin_direction: str of pin_direction s3 is optional, only needed if 16 pins are used, 8 pins possible with s0-s2. pmux can be read like a list: value=amux[2] pmux can be set like a list: amux[2]=1 """ if mux: self.s0 = s0 self.s1 = s1 self.s2 = s2 self.s3 = s3 self.mux = mux else: if type(s0) in (int, str): self.s0 = PyPin(s0, machine.Pin.OUT) self.s1 = PyPin(s1, machine.Pin.OUT) self.s2 = PyPin(s2, machine.Pin.OUT) if s3: self.s3 = PyPin(s3, machine.Pin.OUT) else: self.s0 = s0 self.s1 = s1 self.s2 = s2 if s3: self.s3 = s3 if s3: self.__size = 16 else: self.__size = 8 self._selected_pin = None if pin_direction not in dir(machine.Pin): raise TypeError( "Pin_direction {!r} does not exist".format(pin_direction)) if pin_pull not in dir(machine.Pin): raise TypeError("Pin_pull {!s} does not exist".format(pin_pull)) self.pin = PyPin(pin, getattr(machine.Pin, pin_direction), pin_pull)
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()
class WIFILED(ComponentBase): def __init__(self, pin, active_high=True, **kwargs): super().__init__(COMPONENT_NAME, __version__, discover=False, unit_index=0, **kwargs) self.pin = Pin(pin, machine.Pin.OUT, value=0 if active_high else 1) self._active_high = active_high self._next = [] asyncio.create_task(self._loop()) async def _loop(self): mqtt = config.getMQTT() mqtt.registerWifiCallback(self._wifiChanged) mqtt.registerConnectedCallback(self._reconnected) await self._flash(500, 1) sta = network.WLAN(network.STA_IF) st = time.ticks_ms() while True: while self._next: await self._flash(*self._next.pop(0)) await asyncio.sleep(1) if time.ticks_diff(time.ticks_ms(), st) > 60000: # heartbeat st = time.ticks_ms() if sta.isconnected(): await self._flash(20, 1) await asyncio.sleep_ms(250) await self._flash(20, 1) else: await self._flash(500, 3) await asyncio.sleep_ms(500) async def _flash(self, duration, iters): for _ in range(iters): self.pin.value(1 if self._active_high else 0) await asyncio.sleep_ms(duration) self.pin.value(0 if self._active_high else 1) await asyncio.sleep_ms(duration) async def _wifiChanged(self, state): if state is True: self._next.append((50, 2)) else: self._next.append((500, 3)) async def _reconnected(self, client): self._next.append((100, 5))
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()
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
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()
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()
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()
class LEDNotification(ComponentButton): 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() async def _on(self): for _ in range(self.iters): self.pin.value(1) await asyncio.sleep_ms(self.on_time) self.pin.value(0) await asyncio.sleep_ms(self.off_time)
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
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())
class Mux: def __init__(self, shift_pin, store_pin, data_pin, number_multiplexer=1): self.shcp = PyPin(shift_pin, machine.Pin.OUT) self.stcp = PyPin(store_pin, machine.Pin.OUT) self.ds = PyPin(data_pin, machine.Pin.OUT) self.__data = bytearray() for i in range(0, 8 * number_multiplexer): self.__data.append(0) self.__size = number_multiplexer self.write() def write(self): self.stcp.value(0) for i in range((8 * self.__size) - 1, -1, -1): self.shcp.value(0) self.ds.value(self.__data[i]) self.shcp.value(1) self.stcp.value(1) def __setitem__(self, a, b): if b != 1 and b != 0: raise ValueError("Value must be 1 or 0") self.__data[a] = b def __getitem__(self, a): return self.__data[a] def __delitem__(self, a): self.__data[a] = 0 def set(self, i): self.__data[i] = 1 def clear(self, i): self.__data[i] = 0 def getSize(self): """ Get number of pins""" return self.__size * 8 def Pin(self, i, *args, **kwargs): return Pin(self, i)
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))
def __init__(self, pin, active_high=True, mqtt_topic=None, friendly_name=None, discover=True): 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, instance_name="{!s}_{!s}".format(COMPONENT_NAME, pin), discover=discover) self.pin = Pin(pin, machine.Pin.OUT, value=0 if active_high else 1) self._state = not active_high self._frn = friendly_name self._active_high = active_high
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()