Ejemplo n.º 1
0
 def led2_setup(self):
     LED_2_pin = Pin(2, Pin.OUT)
     LED_2_on = 1
     self.led_2 = RelayControl(name="Led2",
                               _pin=LED_2_pin,
                               on_value=LED_2_on,
                               default=LED_2_on)
Ejemplo n.º 2
0
    def _make_realay(self, key, value):
        relay_pin = value["pin"]
        relay_name = "{}".format(key)
        relay_pin = Pin(relay_pin, Pin.OUT)
        rl_on = 0
        relay = RelayControl(name=relay_name,
                             _pin=relay_pin,
                             on_value=rl_on,
                             default=1 - rl_on)
        relay.set_callback(self.relay_cb)
        self.relays[relay_name] = relay

        if self.mbus:

            self.mbus.sub("RC_{}".format(key), {
                "id": relay_name,
                "func": self.control_relay
            })

            self.mbus.pub({
                "id": "TOPIC",
                "msg": {
                    "name": relay_name,
                    "data": "set"
                }
            })

            self.mbus.pub({
                "id": "TOPIC",
                "msg": {
                    "name": relay_name,
                    "data": "state"
                }
            })
Ejemplo n.º 3
0
    def led2_setup(self):

        LED_2_pin = Pin(2, Pin.INOUT)
        LED_2_on = 1

        self.led_2 = RelayControl(name="Led2",
                                  _pin=LED_2_pin,
                                  on_value=LED_2_on,
                                  default=LED_2_on)
        self.led_2.set_callback(self.relay_cb)
Ejemplo n.º 4
0
    def __init__(self, mbus):

        led_pin = 2

        led_name = "LED_{}_HEARTBEAT".format(led_pin)
        led_pin = Pin(led_pin, Pin.OUT)
        self.led = RelayControl(name=led_name, _pin=led_pin, on_value=1, default=1)
        mbus.sub(led_name, {"id": "WIFI", "func": self.control_heartbeat})

        self.on_ms = 500
        self.off_ms = 5000

        # uasyncio
        loop = asyncio.get_event_loop()
        loop.create_task(self._led_blink())
Ejemplo n.º 5
0
    def relay_setup(self):
        sw_1_pin = Pin(26, Pin.OUT)
        sw_1_on = 0
        self.sw_1 = RelayControl(name="sw1",
                                 _pin=sw_1_pin,
                                 on_value=sw_1_on,
                                 default=1 - sw_1_on)
        self.sw_1.set_callback(self.relay_cb)

        sw_2_pin = Pin(27, Pin.OUT)
        sw_2_on = 0
        self.sw_2 = RelayControl(name="sw2",
                                 _pin=sw_2_pin,
                                 on_value=sw_2_on,
                                 default=1 - sw_2_on)
        self.sw_2.set_callback(self.relay_cb)
Ejemplo n.º 6
0
class Runner:
    '''

    '''

    # init
    def __init__(self,
                 name=None,
                 debug=False,
                 control_pin=None,
                 control_thread=None):

        self.control_pin = control_pin
        self.control_thread = control_thread
        self.name = name
        self.debug = debug

        self.led2_setup()

        self.control_pin.set_callback(self.b4_cb)

    #BUTTON CALLBACK

    def b4_cb(self):

        if self.control_pin.state == "ON":
            self.led_2.change_state()

        if self.debug:
            print("Button is = %s" % self.control_pin.state)

    def led2_setup(self):

        LED_2_pin = Pin(2, Pin.INOUT)
        LED_2_on = 1

        self.led_2 = RelayControl(name="Led2",
                                  _pin=LED_2_pin,
                                  on_value=LED_2_on,
                                  default=LED_2_on)
        self.led_2.set_callback(self.relay_cb)

    #RELAY CALLBACK
    def relay_cb(self, relay):

        if self.debug:
            print("Led: %s = %s" % (relay.name, relay.state))
Ejemplo n.º 7
0
class HeartbeatActivate:

    def __init__(self, mbus):

        led_pin = 2

        led_name = "LED_{}_HEARTBEAT".format(led_pin)
        led_pin = Pin(led_pin, Pin.OUT)
        self.led = RelayControl(name=led_name, _pin=led_pin, on_value=1, default=1)
        mbus.sub(led_name, {"id": "WIFI", "func": self.control_heartbeat})

        self.on_ms = 500
        self.off_ms = 5000

        # uasyncio
        loop = asyncio.get_event_loop()
        loop.create_task(self._led_blink())

        
    def control_heartbeat(self, key, msg):

        if msg["name"] == "ap_status":
            if msg["data"]:
                self.on_ms = 500
                self.off_ms = 1000

        elif msg["name"] == "sta_status":
            if msg["data"]:
                self.on_ms = 500
                self.off_ms = 10000


    async def _led_blink(self):

        while True:
            self.led.on()
            await asyncio.sleep_ms(self.on_ms)
            self.led.off()
            await asyncio.sleep_ms(self.off_ms)
Ejemplo n.º 8
0
    def __init__(self):
        threading.Thread.__init__(self)
        self.__firstMoistureFail = False
        self.__wateredLastRound = False
        self.__lastMoistureMeasure = 0.0
        self.__waterTimes = []
        self.__waterLeft = None

        self.__nightLightOn = False
        self.__lastSpectrumMeasure = 0
        self.__lastIrMeasure = 0
        self.__aggregateSpectrum = 0
        self.__aggregateIr = 0
        self.__lightOnTime = 0
        self.__nightTime = 0
        self.__prevNightTime = 0

        self.__lastTempMeasure = 0  # degrees celsius

        self.__plantJson = None
        self.__plantTypeJson = None
        self.__plantName = None
        self.__plantTime = None
        self.SOIL_MOISTURE_LEVEL = None
        self.ENOUGH_SPECTRUM = None
        self.ENOUGH_IR = None

        self.__readJson()

        self.__lastLoopTime = 0
        self.__running = True

        GPIO.setwarnings(False)
        self.__light = LightSensor()
        self.__moisture = MoistureSensor()
        self.__relayControl = RelayControl()
        self.__temp = TempSensor()
Ejemplo n.º 9
0
class Runner:
    '''

    '''

    # init
    def __init__(self, debug=False):

        self.debug = debug
        self.wlan = False
        self.mqtt_bus = {}
        self.btn_ctrl = False
        self.button_control()

    #BUTTON CHECK
    def button_push_check(self):

        while True:
            self.btn_ctrl.push_check
            _thread.wait(200)

    def button_control(self, pin=4):

        ctrl_pin = Pin(pin, Pin.IN, Pin.PULL_UP)
        self.btn_ctrl = ButtonControl(name="B4",
                                      _pin=ctrl_pin,
                                      debug=self.debug,
                                      on_value=0,
                                      off_value=1)
        self.btn_ctrl.start()

        _ = _thread.stack_size(5 * 1024)
        th1 = _thread.start_new_thread("THRD_B_C", self.button_push_check, ())

    def config(self):

        print("Start Config")

        self.wifi()

        self.led2_setup()
        self.btn_ctrl.set_callback(self.b4_cb)

        self.client_id = b"esp32_" + ubinascii.hexlify(machine.unique_id())
        #iot.eclipse.org
        #192.168.100.240

        self.config = {
            "broker": 'iot.eclipse.org',
            "port": 1883,
            "delay_between_message": -500,
            "client_id": self.client_id,
            "topic": b"devices/" + self.client_id + "/#",
            "ping": b"devices/" + self.client_id + "/ping",
        }

        if self.wlan_check():
            self.http()
            self.start_mqtt()

    def wlan_check(self):

        if self.wlan:
            return self.wlan.isconnected()
        else:
            return False

    #mqtt
    def mqtt_sub_cb(self, topic, msg):

        self.c_mqtt.status == 0

        if topic == self.config['ping']:

            if msg.decode() == "1":
                self.c_mqtt.status == 1

        if self.debug:
            print("Sub Message: Pub: %s, %s" % (topic.decode(), msg.decode()))

    def mqtt(self):
        self.c_mqtt = False
        try:
            self.c_mqtt = MQTTClient(self.config['client_id'],
                                     self.config['broker'],
                                     self.config['port'],
                                     timeout=1,
                                     sbt=self.config['topic'],
                                     debug=True)

            self.c_mqtt.set_callback(self.mqtt_sub_cb)

        except (OSError, ValueError):
            print("Couldn't connect to MQTT")

    def mqtt_check(self):

        delay_send_message = -300
        delay_wait_message = -1000

        while True:
            if self.wlan_check():

                if self.c_mqtt and self.c_mqtt.status == 0:
                    self.c_mqtt.communicate()

                if self.c_mqtt and self.c_mqtt.status == 1:

                    retain = False

                    if self.mqtt_bus:

                        for key, value in self.mqtt_bus.items():
                            t_start = utime.ticks_ms()

                            if value:
                                # DEBUG
                                if self.debug:
                                    print("Message Ready: Pub: %s, %s" %
                                          (key, value))

                                result = self.c_mqtt.publish(
                                    self.config[key], bytes(value, 'utf-8'),
                                    retain)

                                while utime.ticks_diff(t_start, utime.ticks_ms(
                                )) >= delay_send_message:
                                    yield None

                                if result == 1:
                                    self.mqtt_bus[key] = None

                                # DEBUG
                                if self.debug:
                                    print("Result pub to MQTT", result)

                    #wait_message
                    w_t_start = utime.ticks_ms()
                    while utime.ticks_diff(
                            w_t_start, utime.ticks_ms()) >= delay_wait_message:
                        yield None

                    print("Before wait_msg")
                    self.c_mqtt.wait_msg()
                    self.mqtt_bus['ping'] = '1'
            # else:
            #     if self.debug:
            #         print("Error: No Wifi connect")

            yield True

    def _run_mqtt_process(self):

        pubwait = self.mqtt_check()

        while True:
            try:
                next(pubwait)
            except StopIteration:
                if self.debug:
                    print("StopIteration")

            _thread.wait(1000)

    def start_mqtt(self):

        self.mqtt()

        _thread.stack_size(4 * 1024)
        self._http_thread = _thread.start_new_thread("MqttSe",
                                                     self._run_mqtt_process,
                                                     ())

    #http
    def http(self):

        _routeHandlers = []

        # System
        _routeHandlers.append(SystemHandler(debug=self.debug).route_handler)
        _routeHandlers.append(
            LedHandler(debug=self.debug, relay=self.led_2).route_handler)

        if self.debug:
            print("Routes = %s" % _routeHandlers)

        server_sehttp = SimpleHttp(port=80,
                                   web_path="/flash/www",
                                   debug=self.debug,
                                   route_handlers=_routeHandlers)
        server_sehttp.start()

        if server_sehttp.started:
            server_sehttp_runner = ProcessRuner(http_server=server_sehttp,
                                                debug=self.debug)
            server_sehttp_runner.start_http()

    #wifi
    def wifi(self):

        print("")
        print("Starting WiFi ...")
        sta_if = network.WLAN(network.STA_IF)
        _ = sta_if.active(True)
        sta_if.connect("WIFI", "PASSWORD")
        utime.sleep_ms(10000)

        if sta_if.isconnected():
            ifcfg = sta_if.ifconfig()
            print("WiFi started, IP:", ifcfg[0])
            self.wlan = sta_if
            network.ftp.start(user="******",
                              password="******",
                              buffsize=1024,
                              timeout=300)

        else:
            print("No connect to WiFi ...")

    #BUTTON CALLBACK

    def b4_cb(self):

        if self.btn_ctrl.state == "ON":
            self.led_2.change_state()

        if self.debug:
            print("Button is = %s" % self.btn_ctrl.state)

    def led2_setup(self):

        LED_2_pin = Pin(2, Pin.INOUT)
        LED_2_on = 1

        self.led_2 = RelayControl(name="Led2",
                                  _pin=LED_2_pin,
                                  on_value=LED_2_on,
                                  default=LED_2_on)
        self.led_2.set_callback(self.relay_cb)

    #RELAY CALLBACK
    def relay_cb(self, relay):

        if self.debug:
            print("Led: %s = %s" % (relay.name, relay.state))
Ejemplo n.º 10
0

import machine, _thread
from machine import Pin
from relay_control import RelayControl
from button_control import ButtonControl

_debug = True
_message = "run in ... ."

#Led
LED_2_pin = Pin(2, Pin.INOUT)
LED_2_on = 1
LED_2 = RelayControl(name="Led2", _pin=LED_2_pin, on_value=LED_2_on, default=LED_2_on)

#BUTTON

b4_pin = Pin(4, Pin.IN, Pin.PULL_UP)
b4 = ButtonControl(name="B4", _pin=b4_pin, debug=True, on_value=0, off_value=1) #TTP223 Active Gnd, Defaul VCC

def b4_cb():

    if b4.state == "ON":
        LED_2.change_state()

    if _debug:
        print("Button is = %s" % b4.state)
        print("Led is  = %s" % LED_2.state)


Ejemplo n.º 11
0
from seven_segment import CustomSevenSegment
from temp_logger import TempLogger
from relay_control import RelayControl
import time
import datetime

# {'probe': 91.4, 'ambient': 92.075, 'time': '2018-09-03 16:02:28'}

relay_pin = 21
pump = RelayControl(relay_pin)

logger = TempLogger(1)
display = CustomSevenSegment()

pump.enable_relay()

while (True):
    time.sleep(0.25)

    temp_info = logger.get_temperature_readings()
    probe_temp = int(temp_info['probe'])
    display.display_temp(probe_temp)

Ejemplo n.º 12
0
 def __init__(self, pin):
     RelayControl.__init__(self, pin)
     self.on_time = 0
     self.off_time = 0
Ejemplo n.º 13
0
class Runner():
    def __init__(self):

        loop = asyncio.get_event_loop()
        self.normal = "start"
        self.service = {}

        #FTP
        self.ftpd = FTPClient(port=25)

        #telnet
        self.telnet = TelnetServer()

        #button control
        self.b4_setup()

        #LED - Heartbeat
        self.led2_setup()
        loop.create_task(self._heartbeat())

        #WIFI
        self.wifi = WifiManager()
        loop.create_task(self.wifi.sta_start())

        #services
        self.service["wifi_STA"] = False
        self.service["wifi_AP"] = False

        self.service["ftp_STA"] = False
        self.service["ftp_AP"] = False

        self.service["telnet"] = False

        self.service["mqtt"] = False
        self.mqtt = False

        self.service["http"] = False

    def _config(self):
        #Relay

        self.relay_setup()

        #MQTT
        from mqttse import MQTTClient

        self.mqtt = MQTTClient(client_id)

        # "local1": "192.168.100.240",
        # "local2": "192.168.254.1",
        # "eclipse": "iot.eclipse.org"

        self.mqtt.server = "192.168.100.240"

        self.mqtt.set_callback(self.mqtt_sub_cb)

        self.mqtt.set_topic("status", "status")
        self.mqtt.set_topic("services", "services")

        self.mqtt.set_topic("sw1_set", "sw1/set")
        self.mqtt.set_topic("sw1_state", "sw1/state")

        self.mqtt.set_topic("sw2_set", "sw2/set")
        self.mqtt.set_topic("sw2_state", "sw2/state")

        #i2c
        # esp32i2cPins = {'sda': 23, 'scl': 22}
        # sclPin = esp32i2cPins['scl']
        # sdaPin = esp32i2cPins['sda']
        i2c = I2C(scl=Pin(22), sda=Pin(23))

        #si7021
        from si7021 import SI7021
        self.s_si = SI7021(i2c)
        self.s_si.read_delay = 30
        self.s_si.sensor_detect()
        self.s_si.start()

        self.mqtt.set_topic("si_t", "si/temperature")
        self.mqtt.set_topic("si_h", "si/humidity")

        self.s_si.set_callback(self.s_si_cb)

        #bmp180
        from bmp180 import BMP180
        self.s_bmp = BMP180(i2c)
        self.s_bmp.read_delay = 30
        self.s_bmp.sensor_detect()
        self.s_bmp.start()

        self.mqtt.set_topic("bmp_t", "bmp/temperature")
        self.mqtt.set_topic("bmp_h", "bmp/pressure")
        self.mqtt.set_topic("bmp_a", "bmp/altitude")

        self.s_bmp.set_callback(self.s_bmp_cb)

        #http

        from httpse import HTTPSE
        from httpse.route_system import SystemHandler
        from httpse.route_led import LedHandler

        _routeHandlers = []
        _routeHandlers.append(SystemHandler().route_handler)
        _routeHandlers.append(LedHandler(relay=self.sw_1).route_handler)

        self.http = HTTPSE(route_handlers=_routeHandlers)

    def s_bmp_cb(self):

        if self.mqtt:
            self.mqtt.mqtt_bus["bmp_t"] = self.s_bmp.temperature
            self.mqtt.mqtt_bus["bmp_h"] = self.s_bmp.pressure
            self.mqtt.mqtt_bus["bmp_a"] = self.s_bmp.altitude

    def s_si_cb(self):

        if self.mqtt:
            self.mqtt.mqtt_bus["si_t"] = self.s_si.temperature
            self.mqtt.mqtt_bus["si_h"] = self.s_si.humidity

    #MQTT
    def mqtt_sub_cb(self, topic, msg):

        # print("Sub Message: Pub: %s, %s" % (topic.decode(), msg.decode()))
        # print("TOPIC sw1_set , %s" % (self.mqtt.topics['sw1_set']))

        if topic.decode() == self.mqtt.topics['sw1_set']:
            # print("1")

            if msg.decode() == "ON":
                # print("on")
                self.sw_1.on()

            if msg.decode() == "OFF":
                # print("off")
                self.sw_1.off()

        if topic.decode() == self.mqtt.topics['sw2_set']:

            if msg.decode() == "ON":
                self.sw_2.on()
            if msg.decode() == "OFF":
                self.sw_2.off()

    # BUTTON b4
    def b4_setup(self):
        pin = 4
        ctrl_pin = Pin(pin, Pin.IN, Pin.PULL_UP)
        self.btn_ctrl = ButtonControl(name="B4",
                                      _pin=ctrl_pin,
                                      debug=True,
                                      on_value=0,
                                      off_value=1)
        self.btn_ctrl.set_callback(self.b4_cb)

    def b4_cb(self):

        if self.btn_ctrl.state == "ON":
            if self.normal == "start":
                self.normal = "fail"
                print("Start Fail Safe Mode")

            print("Button is = %s" % self.btn_ctrl.state)

        if self.btn_ctrl.state == "OFF":
            print("Button is = %s" % self.btn_ctrl.state)

    # Blink flash LED
    def led2_setup(self):
        LED_2_pin = Pin(2, Pin.OUT)
        LED_2_on = 1
        self.led_2 = RelayControl(name="Led2",
                                  _pin=LED_2_pin,
                                  on_value=LED_2_on,
                                  default=LED_2_on)

    async def _heartbeat(self):
        while True:

            if not self.wifi.status and not self.wifi.status_ap:
                self.led_2.on()
                await asyncio.sleep_ms(100)
                self.led_2.off()
                await asyncio.sleep_ms(200)

            if self.wifi.status:
                self.led_2.off()
                await asyncio.sleep_ms(500)
                self.led_2.on()
                await asyncio.sleep_ms(5000)

            if self.wifi.status_ap:
                self.led_2.off()
                await asyncio.sleep_ms(200)
                self.led_2.on()
                await asyncio.sleep_ms(1000)

    # RELAY
    def relay_setup(self):
        sw_1_pin = Pin(26, Pin.OUT)
        sw_1_on = 0
        self.sw_1 = RelayControl(name="sw1",
                                 _pin=sw_1_pin,
                                 on_value=sw_1_on,
                                 default=1 - sw_1_on)
        self.sw_1.set_callback(self.relay_cb)

        sw_2_pin = Pin(27, Pin.OUT)
        sw_2_on = 0
        self.sw_2 = RelayControl(name="sw2",
                                 _pin=sw_2_pin,
                                 on_value=sw_2_on,
                                 default=1 - sw_2_on)
        self.sw_2.set_callback(self.relay_cb)

    def relay_cb(self, relay):

        if self.mqtt:
            self.mqtt.mqtt_bus[relay.name + '_state'] = relay.get_state()

        print("SW: %s = %s" % (relay.name, relay.state))

    #Main Loop
    async def _run_main_loop(self):
        # Loop forever
        mins = 0
        while True:
            gc.collect()  # For RAM stats.
            mem_free = gc.mem_free()
            mem_alloc = gc.mem_alloc()

            print("STA status: {}".format(self.wifi.status))
            print("AP status: {}".format(self.wifi.status_ap))

            self.status = {
                "Uptime": "{}".format(mins),
                "MemFree": "{}".format(mem_free),
                "MemAlloc": "{}".format(mem_alloc)
            }

            print("Status: {}".format(self.status))
            print("Services: {}".format(self.service))
            # print("Uptime: {}".format(mins))
            # print("MemFree: {}".format(mem_free))
            # print("MemAlloc: {}".format(mem_alloc))
            # print("Services: {}".format(self.service))

            if self.mqtt:
                self.mqtt.mqtt_bus["status"] = ("{}".format(self.status))
                self.mqtt.mqtt_bus["services"] = ("{}".format(self.service))

            mins += 1

            await asyncio.sleep(60)

    #Service Loop
    async def _run_service_loop(self):

        while True:

            if self.wifi.status:
                self.service["wifi_STA"] = self.wifi.wlan().ifconfig()[0]

            else:
                self.service["wifi_STA"] = False

            if self.wifi.status_ap:
                self.service["wifi_AP"] = self.wifi.accesspoint().ifconfig()[0]
            else:
                self.service["wifi_AP"] = False

            if self.service["wifi_STA"]:

                if not self.service["ftp_STA"]:
                    self.service["ftp_STA"] = self.ftpd.run(
                        self.service["wifi_STA"])

                if not self.service["mqtt"] and self.mqtt:
                    self.service["mqtt"] = self.mqtt.run()

                if not self.service["telnet"]:
                    self.service["telnet"] = self.telnet.start()

                if not self.service["http"] and self.http:
                    self.service["http"] = self.http.start()

            if self.service["wifi_AP"]:

                if not self.service["ftp_AP"]:
                    self.service["ftp_AP"] = self.ftpd.run(
                        self.service["wifi_AP"])

                if not self.service["telnet"]:
                    self.service["telnet"] = self.telnet.start()

                if not self.service["http"] and self.http:
                    self.service["http"] = self.http.start()

            await asyncio.sleep(10)

    async def main(self):

        print("Wait: Press Control Button")
        await asyncio.sleep(10)

        if self.normal is not "fail":
            print("Start: Normal Mode")
            self._config()
            self.normal = "run"

        log.info("Start Service Loop")
        loop = asyncio.get_event_loop()
        loop.create_task(self._run_service_loop())

        log.info("Start main_loop")
        while True:
            try:
                await self._run_main_loop()
            except Exception as e:
                print("Global communication failure: %s " % e)