Exemplo n.º 1
0
def main():
    from m5stack import lcd, buttonA
    from mpu9250 import MPU9250
    from time import sleep_ms
    from machine import I2C
    import network
    
	# lcd.font(lcd.FONT_Small, transparent=True, fixedwidth=False)

    try:
        sta_if = network.WLAN(network.STA_IF)
        if sta_if.active() == True:
            m_acc = network.mqtt('acc', 'mqtt://srdmobilex.ddns.net', port=65530, clientid='a')
            m_gyro = network.mqtt('gyro', 'mqtt://srdmobilex.ddns.net', port=65530, clientid='g')
            m_acc.start()
            m_gyro.start()
            m_acc.subscribe('acc', 2)
            m_gyro.subscribe('gyro', 0)

        i2c = I2C(sda = 21, scl = 22)
        
        imu = MPU9250(i2c)

        lcd.clear()
        lcd.setColor(lcd.WHITE)
        lcd.font(lcd.FONT_Small, transparent=False)

        counter = 0

        while not buttonA.isPressed():
            accel = imu.acceleration
            gyro = imu.gyro
            mag = imu.magnetic
            lcd.print("ACCEL: {:+7.2f}  {:+7.2f}  {:+7.2f}".format(accel[0], accel[1], accel[2]), lcd.CENTER, 20)
            lcd.print("GYRO:  {:+7.2f}  {:+7.2f}  {:+7.2f}".format(gyro[0], gyro[1], gyro[2]), lcd.CENTER, 40)
            lcd.print("MAG:   {:+7.2f}  {:+7.2f}  {:+7.2f}".format(mag[0], mag[1], mag[2]), lcd.CENTER, 60)
            if sta_if.active() == True:
                m_acc.publish('acc', '{:+7.2f},{:+7.2f},{:+7.2f}'.format(accel[0], accel[1], accel[2]) + '(%d)'%counter)
                m_gyro.publish('gyro', '{:+7.2f}  {:+7.2f}  {:+7.2f}'.format(gyro[0], gyro[1], gyro[2]) + '(%d)'%counter)
                counter += 1
            sleep_ms(20)

        m_acc.free()
        m_gyro.free()
        i2c.deinit()
        lcd.print('Exit.', 0, 100)
    except:
        return -1
Exemplo n.º 2
0
    def __init__(self, data_cb=None, enable_eyes=False, enable_buzzer=False, enable_accelero=False):
        self.id = machine.nvs_getstr('token')
        self.wifi_ssid = machine.nvs_getstr('ssid')
        self.wifi_password = machine.nvs_getstr('pwd')
        self.mqtt_server = machine.nvs_getstr('mqtt_server')
        self.mqtt_user = machine.nvs_getstr('mqtt_user')
        self.mqtt_password = machine.nvs_getstr('mqtt_password')

        self.wifi = network.WLAN(network.STA_IF)
        self.mqtt = network.mqtt(self.id, self.mqtt_server,
                                 user=self.mqtt_user,
                                 password=self.mqtt_password,
                                 cleansession=True,
                                 data_cb=data_cb)

        self.button_0 = Button(machine.Pin(36))
        self.button_1 = Button(machine.Pin(39))
        self.touch_0 = machine.TouchPad(machine.Pin(12))
        self.touch_1 = machine.TouchPad(machine.Pin(14))

        i2c_bus = machine.I2C(id=0, scl=machine.Pin(22), sda=machine.Pin(21), freq=100000)

        if enable_eyes:
            self.eyes = Eyes()
            print(Feedback.INF_EYES_ENABLED)

        if enable_buzzer:
            self.buzzer = Buzzer()
            print(Feedback.INF_BUZZER_ENABLED)

        if enable_accelero:
            self.accelero = AcceleroMeter(i2c_bus)
            print(Feedback.INF_ACCELERO_ENABLED)
Exemplo n.º 3
0
    def __init__(self,
                 host,
                 user,
                 password,
                 base_path,
                 client_id,
                 debug=False):
        self.base_path = base_path
        self.debug = debug
        self.callback = None

        self.mqtt = network.mqtt("mqtt",
                                 host,
                                 user=user,
                                 password=password,
                                 autoreconnect=True,
                                 data_cb=self.on_message_receive,
                                 cleansession=True,
                                 clientid=client_id)

        self.mqtt.start()

        log.info("MQTT: Started. Trying to connect ...")

        while not self.mqtt.status()[0] == 2:
            time.sleep_ms(200)

        log.success("MQTT: Connected")
        self.mqtt.subscribe('{}+'.format(self.base_path))
Exemplo n.º 4
0
    def connect_mqtt(self):
        free_brokers = [
            'iot.eclipse.org',
            "mqtt://test.mosquitto.org",
        ]
        mqtt = network.mqtt("mosq-pub",
                            free_brokers[1],
                            cleansession=True,
                            data_cb=self.datacb)

        # Connect to MQTT
        mqtt.start()

        tmo = 0
        while mqtt.status()[0] != 2:
            utime.sleep_ms(100)
            tmo += 1
            if tmo > 80:
                print("Not connected")
                break

        # Subscribe
        self.honk(100)
        utime.sleep_ms(100)
        self.honk(100)
        self.mqtt = mqtt
Exemplo n.º 5
0
 def __init__(self):
     spi = SPI(2, sck=Pin(18), mosi=Pin(23), miso=Pin(19),baudrate=14500000)
     self.display = Display(spi, dc=Pin(17), cs=Pin(5), rst=Pin(16))
     # self.display("连接MQTT服务器...")
     self.mqtt = network.mqtt("otv", "mqtt://t.hsxsix.com", user="******", password="******", 
                     cleansession=True, connected_cb=self.conncb, disconnected_cb=self.disconncb, 
                     subscribed_cb=self.subscb, published_cb=self.pubcb, data_cb=self.datacb)
     self.weather_data = {} 
     self.weather_api = 'http://118.24.144.127/weather/v1?city={}&node=micropython_ssd1351'
     self.weather_tm = Timer(2)
     self.weather_tm.init(period=1000*60*20, 
             mode=self.weather_tm.PERIODIC, callback=self.update_weather)
Exemplo n.º 6
0
def connect_client(host="jack", port=5005, mqtt_client_name=None):
    global mqtt, osc
    print("Querying mDNS", host)
    ip = mdns.queryHost(host, timeout=30000)
    print("Query result:", ip)
    if len(ip) == 0 or 'not found' in ip:
        print("ABORT: Could not resolve host!")
        return False
    if mqtt_client_name is not None:
        mqtt = network.mqtt(mqtt_client_name, "mqtt://" + ip)
        mqtt.start()
    else:  # use OSC
        osc = Client(ip, port)
Exemplo n.º 7
0
    def mqtt(self):
        def __recv(msg):
            self.msg = msg[2]
            print('[%s] Data arrived from topic: %s. (%d)' %
                  (msg[0], msg[1], len(msg[2])))
            self.exec(msg[2])

        self.m = network.mqtt("sync",
                              "mqtt://192.168.31.245",
                              port=1883,
                              data_cb=__recv)
        self.m.start()
        self.m.subscribe(b'sync')
Exemplo n.º 8
0
 def __init__(self,
              topic,
              name='uPy_home_control',
              address='mqtt://192.168.178.65'):
     self.client = network.mqtt(name, address)
     self.callback = {}
     self.client.start()
     while self.client.status()[0] < 2:
         time.sleep(.1)
     self.client.config(data_cb=lambda msg, fun=self._callback: fun(msg))
     self.topic = topic
     #self.client.config(self._callback)
     self.client.subscribe(topic + '/#')
     self.publish('status', 'booting')
Exemplo n.º 9
0
async def async_main(state: state_class):
    numAttempts = 3
    while numAttempts > 0:
        try:
            async with AsyncExitStack as mainStack:
                mainTasks = set()
                mainStack.push_async_callback(cancel_tasks, mainTasks)

                mainTasks.add(asyncio.create_task(mqtt(state)))
                mainTasks.add(asyncio.create_task(light_loop(state)))

                await asyncio.gather(*mainTasks)
        except MqttError as error:
            print(f'Error "{error}". Reconnecting. Attempts Remaining {numAttempts}')
        finally:
            await asyncio.sleep(3)
Exemplo n.º 10
0
 def init(self):
     """ Init logic; connect to wifi, connect to MQTT and setup RTC/NTP """
     self._log('Connecting to wifi ({0})... '.format(
         self._wifi_credentials[0]),
               tft=True)
     self._wlan = network.WLAN(network.STA_IF)
     self._wlan.active(True)
     self._wlan.connect(*self._wifi_credentials)
     safety = 10
     while not self._wlan.isconnected() and safety > 0:
         # Wait for the wifi to connect, max 10s
         time.sleep(1)
         safety -= 1
     self._log('Connecting to wifi ({0})... {1}'.format(
         self._wifi_credentials[0], 'Done' if safety else 'Fail'))
     self._log('Connecting to MQTT...', tft=True)
     if self._mqtt is not None:
         self._mqtt.unsubscribe('emon/#')
     self._mqtt = network.mqtt('emon',
                               self._mqtt_broker,
                               user='******',
                               password='******',
                               data_cb=self._process_data)
     self._mqtt.start()
     safety = 5
     while self._mqtt.status()[0] != 2 and safety > 0:
         # Wait for MQTT connection, max 5s
         time.sleep(1)
         safety -= 1
     self._mqtt.subscribe('emon/#')
     self._log(
         'Connecting to MQTT... {0}'.format('Done' if safety else 'Fail'))
     self._log('Sync NTP...', tft=True)
     self._rtc.ntp_sync(server='be.pool.ntp.org', tz='CET-1CEST-2')
     safety = 5
     while not self._rtc.synced() and safety > 0:
         # Wait for NTP time sync, max 5s
         time.sleep(1)
         safety -= 1
     self._last_update = self._rtc.now()
     self._log('Sync NTP... {0}'.format('Done' if safety else 'Fail'))
     self._tft.text(0, 14, ' ' * 50, self._tft.DARKGREY)  # Clear the line
Exemplo n.º 11
0
 def init(self):
     """ Init logic; connect to wifi, connect to MQTT and setup RTC/NTP """
     self._log('Connecting to wifi ({0})... '.format(self._wifi_credentials[0]), tft=True)
     self._wlan = network.WLAN(network.STA_IF)
     self._wlan.active(True)
     self._wlan.connect(*self._wifi_credentials)
     safety = 10
     while not self._wlan.isconnected() and safety > 0:
         # Wait for the wifi to connect, max 10s
         time.sleep(1)
         safety -= 1
     self._log('Connecting to wifi ({0})... {1}'.format(self._wifi_credentials[0], 'Done' if safety else 'Fail'))
     mac_address = ubinascii.hexlify(self._wlan.config('mac'), ':').decode()
     self._log('Connecting to MQTT...', tft=True)
     if self._mqtt is not None:
         self._mqtt.unsubscribe('emon/#')
     self._mqtt = network.mqtt('emon', self._mqtt_broker, user='******', password='******', clientid=mac_address, data_cb=self._process_data)
     self._mqtt.start()
     safety = 5
     while self._mqtt.status()[0] != 2 and safety > 0:
         # Wait for MQTT connection, max 5s
         time.sleep(1)
         safety -= 1
     self._mqtt.subscribe('emon/#')
     self._log('Connecting to MQTT... {0}'.format('Done' if safety else 'Fail'))
     self._log('Sync NTP...', tft=True)
     self._rtc.ntp_sync(server='be.pool.ntp.org', tz='CET-1CEST-2')
     safety = 5
     while not self._rtc.synced() and safety > 0:
         # Wait for NTP time sync, max 5s
         time.sleep(1)
         safety -= 1
     self._last_update = self._rtc.now()
     self._log('Sync NTP... {0}'.format('Done' if safety else 'Fail'))
     self._log('Initializing Neopixels...', tft=True)
     try:
         self._neopixel = Neopixel(Pin(15), 10, Neopixel.TYPE_RGB)
         self._neopixel.clear()
     except Exception:
         self._neopixel = None
     self._log('Initializing Neopixels... {0}'.format('Available' if self._neopixel is not None else 'Unavailable'))
     self._tft.text(0, 14, ' ' * 50, self._tft.DARKGREY)  # Clear the line
Exemplo n.º 12
0
    def __init__(self,
                 data_cb=None,
                 enable_eyes=False,
                 enable_buzzer=False,
                 enable_accelero=False):
        self.id = machine.nvs_getstr('token')
        self.wifi_ssid = machine.nvs_getstr('ssid')
        self.wifi_password = machine.nvs_getstr('pwd')
        self.mqtt_server = machine.nvs_getstr('mqtt_server')
        self.mqtt_user = machine.nvs_getstr('mqtt_user')
        self.mqtt_password = machine.nvs_getstr('mqtt_password')

        self.wifi = network.WLAN(network.STA_IF)
        self.mqtt = network.mqtt(self.id,
                                 self.mqtt_server,
                                 user=self.mqtt_user,
                                 password=self.mqtt_password,
                                 cleansession=True,
                                 data_cb=data_cb)

        self.button_0 = Button(machine.Pin(36))
        self.button_1 = Button(machine.Pin(39))
        self.touch_0 = machine.TouchPad(machine.Pin(12))
        self.touch_1 = machine.TouchPad(machine.Pin(14))

        i2c_bus = machine.I2C(id=0,
                              scl=machine.Pin(22),
                              sda=machine.Pin(21),
                              freq=100000)

        if enable_eyes:
            self.eyes = Eyes()
            print(Feedback.INF_EYES_ENABLED)

        if enable_buzzer:
            self.buzzer = Buzzer()
            print(Feedback.INF_BUZZER_ENABLED)

        if enable_accelero:
            self.accelero = AcceleroMeter(i2c_bus)
            print(Feedback.INF_ACCELERO_ENABLED)
Exemplo n.º 13
0
def wifi_connect():
    """TODO: Docstring for wifi_connect.
    :returns: TODO

    """
    nic = network.WLAN(network.STA_IF)
    if not nic.isconnected():
        print("Trying to connect to Wifi AP")
        nic.active(True)
        nic.connect(SSID, WIFI_PASSWORD)
        # nic.connect()
        print("Waiting for connection...")
        retries = 0
        while not nic.isconnected():
            if retries >= WIFI_MAX_TRIES:
                force_reset()
            utime.sleep_ms(500)
            print('.', end='')
            retries += 1
    print(nic.ifconfig())
    utime.sleep(1)
    print("Connecting to MQTT broker")
    global client
    SERVER = MQTT_SERVER
    CLIENT_ID = machine.unique_id()
    client = network.mqtt(CLIENT_ID, SERVER,
                          cleansession=True, autoreconnect=True,
                          connected_cb=conncb, disconnected_cb=disconncb,
                          subscribed_cb=subscb, published_cb=pubcb,
                          data_cb=datacb)
    while client.status()[0] is not 1:
        utime.sleep_ms(500)
        print('.', end='')
    print("Subscribing to domoticz topici: {}".format(TOPIC_SUB))
    client.subscribe(TOPIC_SUB)

    return nic
def pubcb(pub):
    print("[{}] Published: {}".format(pub[0], pub[1]))


def datacb(msg):
    #print("[{}] Data arrived from topic: {}, Message:\n".format(msg[0], msg[1]), msg[2])
    pass


TOPIC = b'acc_data'
mqtt = network.mqtt('acc_0',
                    "mqtt://这里需要改为你的matt服务器地址",
                    port=1883,
                    lwt_topic=TOPIC,
                    autoreconnect=True,
                    cleansession=True,
                    connected_cb=conncb,
                    disconnected_cb=disconncb,
                    subscribed_cb=subscb,
                    published_cb=pubcb,
                    data_cb=datacb)
mqtt.start()
while not mqtt.subscribe(TOPIC):
    pass


def tcb(timer):
    acc_data = accelerometer.get_values()
    try:
        mqtt.publish(TOPIC, str(acc_data['AcX'] / 16384 - error_x))
    except:
Exemplo n.º 15
0
    tft.clear()
    artist = zz.get('artist', '')
    if artist:
        try:
            tft.image(0, 0, '/sd/{}.jpg'.format(artist.lower()))
        except:
            pass
    tft.text(5, 5, artist + "\n")

    title = wrap(zz.get('title', ''), 28)  # 28 seems right for DejaVu18
    for line in title:
        tft.text(5, tft.LASTY, line + "\n")


mqttc = network.mqtt(mqtt_id,
                     mqtt_aws_host,
                     connected_cb=conncb,
                     clientid=mqtt_id)
mqttc.start()
sleep(1)
# note got Guru Meditation Error with the publish callback
#mqttc.config(subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb)
mqttc.config(subscribed_cb=subscb, data_cb=datacb)
mqttc.subscribe(topic)


# decrease the volume
def button_hander_a(pin, pressed):
    if pressed:
        print("A pressed")
        try:
            mqttc.publish('sonos/' + loc, json.dumps({"action": "quieter"}))
Exemplo n.º 16
0
def pubcb(pub):
    print("[{}] Published: {}".format(pub[0], pub[1]))


def datacb(msg):
    print(
        "[{}] Data arrived from topic: {}, Message:\n".format(msg[0], msg[1]),
        msg[2])


# mqtt = network.mqtt(name, server [, user, password, port, autoreconnect, clientid, cleansession, keepalive, qos, retain, secure, connected_cb, disconnected_cb, subscribed_cb, unsubscribed_cb, published_cb, data_cb])
mqtt = network.mqtt("loboris",
                    "mqtt.m5stack.com",
                    connected_cb=conncb,
                    disconnected_cb=disconncb,
                    subscribed_cb=subscb,
                    published_cb=pubcb,
                    data_cb=datacb)

# secure connection requires more memory and may not work
# mqtts = network.mqtt("eclipse", "iot.eclipse.org", secure=True, cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb)
'''

# Wait until status is: (1, 'Connected')

mqtt.subscribe('test')
mqtt.publish('test', 'Hi from Micropython')

'''
Exemplo n.º 17
0
    if (int(temp[2]) >= 10 and int(temp[2]) < 20):
        pin_r.duty(0)
        pin_g.duty(50)
        pin_b.duty(50)
        servo.duty(3)
    if (int(temp[2]) >= 20 and int(temp[2]) < 25):
        pin_r.duty(0)
        pin_g.duty(100)
        pin_b.duty(0)
    elif (int(temp[2]) >= 25 and int(temp[2]) < 30):
        pin_r.duty(50)
        pin_g.duty(50)
        pin_b.duty(0)
    elif (int(temp[2]) >= 30):
        servo.duty(7)
        pin_r.duty(100)
        pin_g.duty(0)
        pin_b.duty(0)

local_name = 'diana-2'
unique_id  = 'diana24681342'
mqtt = network.mqtt(local_name,
    'mqtt://broker.hivemq.com',
    clientid=unique_id,
    data_cb=on_data
  )
time.sleep(10)
mqtt.start()
connected = mqtt.subscribe('diana/weather')
print("MQTT connected:", connected)
def pubcb(pub):
    print("[{}] Published: {}".format(pub[0], pub[1]))


def datacb(msg):
    print(
        "[{}] Data arrived from topic: {}, Message:\n".format(msg[0], msg[1]),
        msg[2])


mqtt = network.mqtt("loboris",
                    "mqtt://loboris.eu",
                    user="******",
                    password="******",
                    cleansession=True,
                    connected_cb=conncb,
                    disconnected_cb=disconncb,
                    subscribed_cb=subscb,
                    published_cb=pubcb,
                    data_cb=datacb)
# secure connection requires more memory and may not work
# mqtts = network.mqtt("eclipse", "mqtts//iot.eclipse.org", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb)
# wsmqtt = network.mqtt("eclipse", "ws://iot.eclipse.org:80/ws", cleansession=True, data_cb=datacb)

mqtt.start()

#mqtt.config(lwt_topic='status', lwt_msg='Disconected')
'''

# Wait until status is: (1, 'Connected')
Exemplo n.º 19
0
import gsm, json
from network import mqtt

gsm.debug(True)
gsm.start(tx=17, rx=16, apn="TM", roaming=True, wait=True)
gsm.connect()
gsm.status()
gsm.ifconfig()
client = mqtt("test1",
              "calupietru.duckdns.org",
              port=1883,
              user="******",
              password="******")
client.start()
message = {
    "espid": "Prato",
    "timestamp": None,
    "temperatura": 23,
    "peso": 70.1
}
client.publish("/maia/4", json.dumps(message))
client.publish("/maia/4", json.dumps(message))
client.stop()
gsm.disconnect()
Exemplo n.º 20
0
import time
from umqtt import MQTTClient
import machine, ubinascii, gc, json 
from machine import I2C
from machine import Pin
from machine import DHT
import network
import wifi_connect as wlan
wlan.connect()
d = DHT(Pin(17), DHT.DHT2X)
CLIENT_ID = ubinascii.hexlify(machine.unique_id())
gc.collect()
_connected = True
def conncb(task):
    print("[{}] Connected".format(task)) 
    _connected = True
def disconncb(task):
    print("[{}] Disconnected".format(task))
def subscb(task):
    print("[{}] Subscribed".format(task))
def pubcb(pub):
    print("[{}] Published: {}".format(pub[0], pub[1]))
def datacb(msg):
    print("[{}] Data arrived from topic: {}, Message:\n".format(msg[0], msg[1]), msg[2])
mqtts = network.mqtt("myx", "iot.eclipse.org", secure=True)
mqtts.config(clientid=CLIENT_ID,connected_cb=conncb,subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb)
time.sleep(2)
gc.collect()
def loop():
  while True:
Exemplo n.º 21
0
import network

def conncb(task):
    print("[{}] Connected".format(task))

def disconncb(task):
    print("[{}] Disconnected".format(task))

def subscb(task):
    print("[{}] Subscribed".format(task))

def pubcb(pub):
    print("[{}] Published: {}".format(pub[0], pub[1]))

def datacb(msg):
    print("[{}] Data arrived from topic: {}, Message:\n".format(msg[0], msg[1]), msg[2])

mqtt = network.mqtt("loboris", "loboris.eu", user="******", password="******", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb)

mqtts = network.mqtt("eclipse", "iot.eclipse.org", secure=True, cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb)
Exemplo n.º 22
0
    try:
        z = json.loads(msg[2])
    except Exception as e:
        print(e)
        z = {}

    track_info.update(z)
    chapter = page = 0
    display_image()


# note published callback doesn't seem to do anything
mqttc = network.mqtt(mqtt_id,
                     'mqtt://' + mqtt_aws_host,
                     connected_cb=conncb,
                     cleansession=False,
                     subscribed_cb=subscb,
                     published_cb=pubcb,
                     data_cb=datacb,
                     clientid=mqtt_id)

mqttc.start()
sleep(1)

mqttc.subscribe(sub_topic)


# ButtonA
def button_hander_a(pin, pressed):
    global flag
    global row
    global page
Exemplo n.º 23
0
beeper = machine.PWM(machine.Pin(25, machine.Pin.OUT), freq=294, duty=0)


def on_hit(data):
    name, topic, message = data
    value = int(message)
    print("[{}] Data arrived from topic: {}, Message:\n{}\n".format(
        name, topic, message))
    if value == 1:
        beeper.duty(1)
    else:
        beeper.duty(0)


mqtt = network.mqtt('diana-mpy1',
                    'mqtt://broker.hivemq.com',
                    clientid='diana-43674632',
                    data_cb=on_hit)
mqtt.start()


def b1_press(pin):
    if pin.value():
        print(mqtt.publish('pico/moveright', '0'))
    else:
        print(mqtt.publish('pico/moveright', '1'))


def b0_press(pin):
    if pin.value():
        print(mqtt.publish('pico/moveleft', '0'))
    else:
Exemplo n.º 24
0
            servo2.duty(0)

def b1_press(pin):
    print('calibrating black')
    global black_val
    black_val = light.read()

def b0_press(pin):
    print('calibrating white')
    global white_val
    white_val = light.read()

b0 = machine.Pin(0, handler=b0_press, trigger=machine.Pin.IRQ_ANYEDGE, debounce=50000, pull=machine.Pin.PULL_UP)
b1 = machine.Pin(35, handler=b1_press, trigger=machine.Pin.IRQ_ANYEDGE, debounce=50000)

mqtt2 = network.mqtt('aaron1', 'mqtt://broker.hivemq.com', clientid='robot09410948123', data_cb=on_data)
mqtt2.start()
time.sleep(2)
mqtt2.subscribe('pico/moveleft')
mqtt2.subscribe('pico/moveright')

while True:
    threshold = (black_val + white_val) / 2
    if light.read() < threshold and hit_obstacle:
        mqtt2.publish('pico/hit', '0')
        hit_obstacle = False
        print('white')
        led.value(0)
    elif light.read() > threshold and not hit_obstacle:
        mqtt2.publish('pico/hit', '1')
        hit_obstacle = True
Exemplo n.º 25
0
#touch=TouchPad(14,lambda hid:print('press'),lambda hid :print('hold'),lambda hid:print('release'),hold_repeat_time=.1)
btn=Button(25,lambda hid:log.info('press'),lambda hid :log.info('hold'),lambda hid :root.cmd_select(),hold_repeat_time=.1)
encoder=RotaryEncoder(26,27,lambda val: root.cmd_add(val), freq=5)
root.set_wakeup_pin(25) # to wakeup from deepsleep

root.init(root.ILI9488, width=240, height=320, 
    miso=19, mosi=23, clk=18, cs=5, dc=21, tcs=0,rst_pin=22, backl_pin=4, bgr=False,
    hastouch=root.TOUCH_XPT,backl_on=1, speed=40000000, splash=False, rot=root.LANDSCAPE_FLIP)

#info=gui.Frame(root, bg=screen.BLACK, fg=screen.WHITE)
tk.Label(root, 'Starting wifi...').grid()
root.backlight(100)
root.draw()
connect_wifi()

mqtt = network.mqtt('home_controller', 'mqtt://192.168.178.65')
mqtt.start()

rooms=[('Wohnzi.',[4,7,8]), ('Schlafzi.',[2,3]), ('Bastelzi.',[1,6])]
lights=dict()


def datacb(msg):
    log.debug("[{}] Data arrived from topic: {}, Message:\n".format(msg[0], msg[1]), msg[2])
    topic=msg[1].split('/')
    if len(topic)==3 and topic[0]=='node-red' and topic[1]=='lights' and msg[2]!='get_state':
        log.info('update for light {}: {}'.format(topic[2], msg[2]))
        val=msg[2].split('/')
        lnr=int(topic[2])
        if lnr in lights:            
            lights[lnr][0].val=val[0]#bri
Exemplo n.º 26
0
def init_mqtt():
    global mqtt
    mqtt = network.mqtt("MQTT", secrets.mqtt.host, connected_cb=conncb, data_cb=datacb)
    mqtt.start()
Exemplo n.º 27
0
def patience(client):
    while client.status()[1] in ['Disconnected', 'Stopping']:
        time.sleep_ms(50)


thingspeakUrl = b"mqtt.thingspeak.com"
thingspeakUserId = b"jos"  # EDIT - enter Thingspeak User ID
thingspeakMqttApiKey = "U31KDACARRXDWGSF"  # EDIT - enter Thingspeak MQTT API Key (Needs to be generated)
machine.loglevel('*', machine.LOG_DEBUG)
machine.loglevel('[Mqtt client]', machine.LOG_DEBUG)

#test to broker that does NOT allow lwt
#Do not set CleanSession flag to 0.
client = network.mqtt('client_10713646',
                      "mqtt.thingspeak.com",
                      user='******',
                      password=thingspeakMqttApiKey,
                      cleansession=True)
patience(client)
print(client)

client.stop()
patience(client)
client.free()

#default LWT = none
client = network.mqtt('client_10713646',
                      "mqtt.thingspeak.com",
                      user='******',
                      password=thingspeakMqttApiKey,
                      cleansession=True)
def pubcb(pub):
    print("[{}] Published: {}".format(pub[0], pub[1]))


def datacb(msg):
    print(
        "[{}] Data arrived from topic: {}, Message:\n".format(msg[0], msg[1]),
        msg[2])


mqtt = network.mqtt("does",
                    "mqtt://10.0.29.187",
                    user="******",
                    password="******",
                    cleansession=True,
                    connected_cb=conncb,
                    disconnected_cb=disconncb,
                    subscribed_cb=subscb,
                    published_cb=pubcb,
                    data_cb=datacb)

# secure connection requires more memory and may not work
#mqtts = network.mqtt("eclipse", "mqtts://iot.eclipse.org", cleansession=True, data_cb=datacb)

# mqtt over Websocket can also be used
# mqttws = network.mqtt("eclipse", "ws://iot.eclipse.org:80", cleansession=True, data_cb=datacb)
# mqttwss = network.mqtt("eclipse", "wss://iot.eclipse.org:80", cleansession=True, data_cb=datacb)

# Start the mqtt
print("Connecting to MQtt")
oled.text("Publishing Msg", 0, 20)
Exemplo n.º 29
0
#minimal MQTT

import network, sys, machine
import utime
import uos

import gc
machine.loglevel('[Mqtt client]', machine.LOG_DEBUG)
myMqttClient = bytes("client_123", 'utf-8')
thingspeakUrl = "mqtt.thingspeak.com"
thingspeakUserId = "josverlinde"  # EDIT - enter Thingspeak User ID
thingspeakMqttApiKey = "ZWH8LQHCU7L9ETXA"  # EDIT - enter Thingspeak MQTT API Key (Needs to be generated)
machine.loglevel('[Mqtt client]', machine.LOG_DEBUG)
client = network.mqtt(
    myMqttClient,  #clientID
    thingspeakUrl,  #server
    user=thingspeakUserId,  #user
    password=thingspeakMqttApiKey)
Exemplo n.º 30
0

def pubcb(pub):
    print("[{}] Published: {}".format(pub[0], pub[1]))


def datacb(msg):
    print(
        "[{}] Data arrived from topic: {}, Message:\n".format(msg[0], msg[1]),
        msg[2])


mqtt = network.mqtt("mosq-pub",
                    "mqtt://test.mosquitto.org",
                    cleansession=True,
                    connected_cb=conncb,
                    disconnected_cb=disconncb,
                    subscribed_cb=subscb,
                    published_cb=pubcb,
                    data_cb=datacb)
# secure connection requires more memory and may not work
# mqtts = network.mqtt("eclipse", "mqtts//iot.eclipse.org", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb)
# wsmqtt = network.mqtt("eclipse", "ws://iot.eclipse.org:80/ws", cleansession=True, data_cb=datacb)

mqtt.start()

tmo = 0
while mqtt.status()[0] != 2:
    utime.sleep_ms(100)
    tmo += 1
    if tmo > 80:
        print("Not connected")
Exemplo n.º 31
0
        while True:
            if wifi.ifconfig()[0] != '0.0.0.0':
                print("Connected, IP: {}".format(wifi.ifconfig()[0]))
                break
            if time.ticks_ms() - now > timeout:
                break
    return wifi


# wifi = init_wifi("signalhuset", "signal+huset2017")
# wifi = init_wifi("HomeBox-10E0_5G", "a6cfdf567")
wifi = init_wifi("AndroidAPAD82", "odon3187")

dht = machine.DHT(machine.Pin(2), machine.DHT.DHT11)
# dht.read()  #Returns status, temperature (C) and humidity (%)

local_name = 'diana-1'
unique_id = 'diana246813'
mqtt = network.mqtt(
    local_name,
    'mqtt://broker.hivemq.com',
    clientid=unique_id,
    #optional callbacks here
)

mqtt.start()

while True:
    time.sleep(300)
    print(mqtt.publish('diana/weather', str(dht.read()[1])))