示例#1
0
文件: main.py 项目: davea/sonoff-mqtt
def connect_and_subscribe():
    global client
    client = MQTTClient(machine_id, broker)
    client.set_callback(callback)
    client.connect()
    print("Connected to {}".format(broker))
    for topic in (b'config', b'control'):
        t = topic_name(topic)
        client.subscribe(t)
        print("Subscribed to {}".format(t))
def main(server="localhost"):
    c = MQTTClient("umqtt_client", server)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"foo_topic")
    while True:
        if True:
            # Blocking wait for message
            c.wait_msg()
        else:
            # Non-blocking wait for message
            c.check_msg()
            # Then need to sleep to avoid 100% CPU usage (in a real
            # app other useful actions would be performed instead)
            time.sleep(1)

    c.disconnect()
示例#3
0
wifi_config = read_wifi_config()
wifi = WiFiConnect(wifi_config["wifi_retries"] if "wifi_retries" in
                   wifi_config else 250)
wifi.events_add_connecting(connecting_callback)
wifi.events_add_connected(connected_callback)
wifi_status = wifi.connect(wifi_config["wifi_ssid"], wifi_config["wifi_pass"])

print("mqtt_config >")
mqtt_clientid_prefix = read_mqtt_config()["mqtt_clientid_prefix"]
mqtt_host = read_mqtt_config()["mqtt_broker_ip"]
mqtt_root_topic = read_mqtt_config()["mqtt_root_topic"]

mqtt_clientid = mqtt_clientid_prefix + esp_id

c = MQTTClient(mqtt_clientid, mqtt_host, ssl=mqtt_ssl)
c.set_callback(mqtt_sub)

if isLCD:
    lcd.move_to(14, 0)

try:
    if c.connect() == 0:
        subStr = mqtt_root_topic + esp_id + "/#"
        c.subscribe(subStr)

        print("mqtt log")
        c.publish(mqtt_root_topic, esp_id)  # topic, message (value) to publish

        simple_blink()
        if isLCD:
            lcd.putchar("M")
示例#4
0
def handle_msg(topic, msg):
    # for debugging
    print("topic: ", topic, " msg: ", msg)

    if msg == b'on':
        led.on()
    elif msg == b'off':
        print("off: ", topic, " msg: ", msg)
        led.off()


######## MQTT Client: starting and connecting ##########

# start the MQTT client for this microcontroller
mq.set_callback(handle_msg)
mq.connect()
mq.subscribe(b'led/#')

########## publishing an MQTT message ###############

# code for momentary switch behavior, toggle behavior is below
# Since this is in the top-level while True loop, it's the default behavior
last_button_value = True  # not pressed

while True:
    mq.check_msg()

    button_value = button.value()

    if last_button_value == button_value:
示例#5
0
def main():
    global my_new_msg
    global TOPIC_BASE
    
    mq_fail_count = 0
    tm_pub_th = time.ticks_ms()

    led_onoff(1)

    #- check ap config file
    AP_SSID = 'upy'
    AP_PWD = 'pypypypy'
    ap_config = None
    ap_config_fn = 'ap.txt'
    if ap_config_fn in os.listdir():
        print('ap config here!')
        f = open(ap_config_fn)
        ap_config = f.read()
        f.close()
    if ap_config:
        print( ('ap_config:', ap_config))
        ap_config = ap_config.split('\n')
        AP_SSID = ap_config[0].strip()
        AP_PWD = ap_config[1].strip()
    print('line to: ', (AP_SSID, AP_PWD))
    
    # Default MQTT server to connect to
    server = "iot.eclipse.org"
    CLIENT_ID = ubinascii.hexlify(machine.unique_id()).decode('utf-8')
    topic_light = TOPIC_BASE+"/light"
    topic_t = TOPIC_BASE+'/T'
    topic_h = TOPIC_BASE+'/H'
    topic_msg = TOPIC_BASE+'/msg'
    

    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(AP_SSID, AP_PWD)
    print('connecting to AP')
    while(not wlan.isconnected()):
        print(wlan.ifconfig())
        time.sleep(0.1)
        led_onoff(-1)
    print('connected!  --> ', wlan.ifconfig())

    c = MQTTClient(CLIENT_ID, server)
    # Subscribed messages will be delivered to this callback
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(topic_light)
    print("Connected to %s, subscribed to %s topic" % (server, topic_light))

    # wifi ready, blink led
    for i in range(3):
        led_onoff(1)
        time.sleep(1)
        led_onoff(0)
        time.sleep(1)
    print('I am ready!, ID='+str(CLIENT_ID))
    c.publish(topic_msg, 'I am ready!, ID='+str(CLIENT_ID))

    try:
        while 1:
            if(not wlan.isconnected()):
                # not do any mq operation
                time.sleep(0.1)
                led_onoff(-1)                
                continue
            
            try:
                #c.wait_msg()
                c.check_msg()
                if my_new_msg:
                    c.publish(topic_msg, my_new_msg)
                    my_new_msg = None

                if(time.ticks_ms()-tm_pub_th > 5000):
                    # public some information
                    T, H = dht_get()
                    c.publish(topic_t, str(T))
                    c.publish(topic_h, str(H))
                    
                    tm_pub_th = time.ticks_ms()
                    
            except Exception as e:
                print('wlan:', wlan.isconnected())
                print('ex: ', str(e))
                mq_fail_count+=1
                time.sleep(1)
                
            try:
                if mq_fail_count>5:
                    mq_fail_count=0
                    c = MQTTClient(CLIENT_ID, server)
                    # Subscribed messages will be delivered to this callback
                    c.set_callback(sub_cb)
                    c.connect()
                    c.subscribe(topic_light)
                    print("Connected to %s, subscribed to %s topic" % (server, topic_light))
            except Exception as e:
                print('wlan:', wlan.isconnected())
                print('ex: ', str(e))
                    

            time.sleep(0.001)
                        
    finally:
        c.disconnect()
示例#6
0
            print(methodName)
            method = getattr(le, methodName)
            repeatCount = 1 if 'repeat' not in msg else msg.pop('repeat')
            print(repeatCount)
            try:
                for i in range(repeatCount):
                    method(**msg)
                print('returned OK')
            except:
                sys.print_exception()
                return
        mqtt.check_msg()


mqtt = MQTTClient(netconfig.mqid, netconfig.mqhost, netconfig.mqport)
mqtt.set_callback(mqhandler)
mqtt.connect()
print(netconfig.iptopic)
print(sta.ifconfig()[0])
mqtt.publish(netconfig.iptopic, sta.ifconfig()[0], True)  #retained message
mqtt.subscribe(netconfig.topic)

# number of pixels
n = 14
# strip control gpio
p = 2

le = LightEffects(neopin=2, num=netconfig.ledcount)

webrepl.start()
示例#7
0
    # Toggle the onboard LED. You should probably disable this if
    # messages are being sent at a high rate
    led.value(not led.value())


# Blink the LED every 100ms to indicate we made it into the main.py file
for _ in range(10):
    time.sleep_ms(100)
    led.value(not led.value())  # Toggle the LED
    time.sleep_ms(100)

# Make sure the LED is off
led.high()

# define a time, because we only want to send every 1s but received as fast as possible
# last_time = time.time()

mqtt = MQTTClient(CLIENT_ID, HOST, port=PORT)
# Subscribed messages will be delivered to this callback
mqtt.set_callback(subscriction_callback)
mqtt.connect()
mqtt.subscribe(TOPIC)
print('Connected to {}, subscribed to {} topic.'.format(HOST, TOPIC))

try:
    while 1:
        #micropython.mem_info()
        mqtt.wait_msg()
finally:
    mqtt.disconnect()
示例#8
0
                rgb_tuple = rgb_tuple.split(',')
                try:
                    rgb_tuple = tuple(int(element) for element in rgb_tuple)
                except ValueError:
                    pass
                else:
                    rgb_tuple = tuple(
                        max(0, min(127, element)) for element in rgb_tuple)
                    print('rgb_tuple = %s' % (rgb_tuple, ))
                    for neopixel in neopixels:
                        neopixel.fill(rgb_tuple)
                    for neopixel in neopixels:
                        neopixel.write()

        # Set the message receipt callback function
        client.set_callback(on_message_received)

        # Perform the MQTT connection handshake.
        client.connect()
        connected = True
        last_publish = 0
        last_ping = ticks_ms()
        print('Connected')

        print('Subscribing to topic %s...' % topic)
        client.subscribe(topic)
        print('Subscribed')

    else:

        # Periodically ping the broker consistently with the "keepalive"
  else:
    new_amp = 1

def run():
  fail = False
  while True:
    if new_amp != act_amp:
      set_amp(new_amp)

    try:
      mqtt.check_msg()
    except OSError:
      print('MQTT check msg failed')
      fail = True
  
    if fail: # Wifi was down - https://forum.micropython.org/viewtopic.php?f=16&t=2163
      try:
        connect_mqtt()
        fail = False
      except OSError: # Wifi is still down
        print('MQTT reconnect failed')
        time.sleep(2)


set_amp(act_amp)
switch.irq(trigger=machine.Pin.IRQ_FALLING, handler=switch_pressed)
mqtt.set_callback(mqtt_input)
connect_wifi()
connect_mqtt()
run()
示例#10
0
    if topic == mqtt_subtopic_linked_alert:
        if msg == mqtt_pubtopic_alert_msg_response:
            state['alert_msg_response'] = True
        if msg == mqtt_pubtopic_alert_msg_ok:
            state['alert_msg_ok'] = True
        if msg == mqtt_pubtopic_alert_msg_stop:
            state['alert_msg_stop'] = True
        if msg == mqtt_pubtopic_alert_msg_ready:
            state['alert_msg_ready'] = True
        if msg == mqtt_pubtopic_alert_msg_start:
            state['alert_msg_start'] = True
    elif topic == mqtt_subtopic_linked_alive:
        pass


c.set_callback(sub_cb)


def mqtt_connect():
    print("MQTT connecting.")
    c.connect()
    npd.animation_boot_blocking(neopixel_boot_color, 12, 18)
    print("MQTT Connected.")
    c.subscribe(mqtt_subtopic_linked_alert)
    c.subscribe(mqtt_subtopic_linked_alive)
    npd.animation_boot_blocking(neopixel_boot_color, 18, 24)


# State machine
async def state_machine():
    while True:
示例#11
0
class CayenneMQTTClient:
    """Cayenne MQTT Client class.

    This is the main client class for connecting to Cayenne and sending and receiving data.

    Standard usage:
    * Set on_message callback, if you are receiving data.
    * Connect to Cayenne using the begin() function.
    * Call loop() at intervals (or loop_forever() once) to perform message processing.
    * Send data to Cayenne using write functions: virtualWrite(), celsiusWrite(), etc.
    * Receive and process data from Cayenne in the on_message callback.

    The on_message callback can be used by creating a function and assigning it to CayenneMQTTClient.on_message member.
    The callback function should have the following signature: on_message(message)
    The message variable passed to the callback is an instance of the CayenneMessage class.
    """
    def __init__(self):

        # init ic2 object
        i2c = I2C(scl=Pin(pinScl), sda=Pin(pinSda))  #ESP8266 5/4
        # Scan the i2c bus and verify if the OLED sceen is connected
        print('Scan i2c bus...')

        self.devices = i2c.scan()
        if len(self.devices) == 0:
            print("No i2c device !")
            self.oledIsConnected = False
        else:
            for self.device in self.devices:
                print("OLED found")
                if self.device == addrOled:
                    self.oled = ssd1306.SSD1306_I2C(wSize, hSize, i2c,
                                                    addrOled)
                    self.oledIsConnected = True
        self.client = None
        self.rootTopic = ""
        self.connected = False
        self.on_message = None

    """Initializes the client and connects to Cayenne.
    ssid     is WiFi ssid
    wifiPassword
    username is the Cayenne username.
    password is the Cayenne password.    
    clientID is the Cayennne client ID for the device.
    hostname is the MQTT broker hostname.
    port is the MQTT broker port. Use port 8883 for secure connections.
    logname is the name of the users log if they want the client to log to their logging setup.
    loglevel is the logging level that will be applied to logs.
    """

    def begin(self,
              username,
              password,
              clientid,
              ssid=SSID,
              wifiPassword=PASSWORD,
              hostname='mqtt.mydevices.com',
              port=1883,
              logname=LOG_NAME,
              loglevel=logging.WARNING):
        self.rootTopic = "v1/%s/things/%s" % (username, clientid)
        print("root topic: %s" % self.rootTopic)
        global wlan
        wlan = network.WLAN(network.STA_IF)
        wlan.active(True)
        wlan.disconnect()

        # try to connect to wlan
        print('connecting to network...')
        if self.oledIsConnected:
            self.oled.fill(0)
            self.oled.text("Connect", 0, 0)
            self.oled.text("to WiFi", 0, 10)
            self.oled.show()
        print("Trying to connect to %s" % ssid)
        wlan.connect(ssid, wifiPassword)

        while (wlan.ifconfig()[0] == '0.0.0.0'):
            time.sleep(1)
        print('network config:', wlan.ifconfig())

        if self.oledIsConnected:
            self.ipAddress = wlan.ifconfig()[0]
            self.oled.fill(0)
            self.oled.text("IP:", 0, 0)
            self.oled.text(self.ipAddress[0:8], 0, 10)
            self.oled.text(self.ipAddress[8:], 0, 20)
            self.oled.show()
        print("Connecting to %s" % hostname)

        self.client = MQTTClient(clientid, hostname, 0, username, password)
        self.client.connect()
        self.connected = True

        self.log = logging.getLogger(logname)
        #        if logname == LOG_NAME:
        #            logging.basicConfig(stream=sys.stdout, format='%(message)s', level=loglevel)
        self.log.info("Connecting to %s:%s" % (hostname, port))

        if self.oledIsConnected:
            self.oled.text("Cayenne", 0, 30)
            self.oled.text("MQTT ok", 0, 40)
            self.oled.show()
        # subscribe to the cmd topic
        command_topic = self.getCommandTopic()
        self.client.set_callback(self.client_on_message)
        self.log.info("SUB %s" % command_topic)
        self.client.subscribe(command_topic)

    def client_on_message(self, topic, payload):
        # The callback for when a PUBLISH message is received from the server.
        self.log.info("RCV %s %s" % (topic, payload))
        self.message = CayenneMessage(topic, payload)
        # If there was no error, we send the new channel state, which should be the command value we received.
        self.virtualWrite(self.message.channel, self.message.value)
        # Send a response showing we received the message, along with any error from processing it.
        self.responseWrite(self.message.msg_id, None)
        if self.on_message:
            print("callback with %s %s" % (topic, payload))
            self.msg = (topic, payload)
            self.on_message(self.msg)
        else:
            print("No callback defined")

    def getDataTopic(self, channel):
        """Get the data topic string.

        channel is the channel to send data to.
        """
        return "%s/%s/%s" % (self.rootTopic, DATA_TOPIC, channel)

    def getCommandTopic(self):
        """Get the command topic string."""
        return "%s/%s/+" % (self.rootTopic, COMMAND_TOPIC)

    def getResponseTopic(self):
        """Get the response topic string."""
        return "%s/%s" % (self.rootTopic, RESPONSE_TOPIC)

    def virtualWrite(self, channel, value, dataType="", dataUnit=""):
        """Send data to Cayenne.

        channel is the Cayenne channel to use.
        value is the data value to send.
        dataType is the type of data.
        dataUnit is the unit of the data.
        """
        if (self.connected):
            topic = self.getDataTopic(channel)
            if dataType:
                payload = "%s,%s=%s" % (dataType, dataUnit, value)
            else:
                payload = value
            self.mqttPublish(topic, payload)

    def responseWrite(self, msg_id, error_message):
        """Send a command response to Cayenne.

        This should be sent when a command message has been received.
        msg_id is the ID of the message received.
        error_message is the error message to send. This should be set to None if there is no error.
        """
        if (self.connected):
            topic = self.getResponseTopic()
            if error_message:
                payload = "error,%s=%s" % (msg_id, error_message)
            else:
                payload = "ok,%s" % (msg_id)
            self.mqttPublish(topic, payload)

    def celsiusWrite(self, channel, value):
        """Send a Celsius value to Cayenne.

        channel is the Cayenne channel to use.
        value is the data value to send.
        """
        self.virtualWrite(channel, value, TYPE_TEMPERATURE, UNIT_CELSIUS)

    def fahrenheitWrite(self, channel, value):
        """Send a Fahrenheit value to Cayenne.

        channel is the Cayenne channel to use.
        value is the data value to send.
        """
        self.virtualWrite(channel, value, TYPE_TEMPERATURE, UNIT_FAHRENHEIT)

    def kelvinWrite(self, channel, value):
        """Send a kelvin value to Cayenne.

        channel is the Cayenne channel to use.
        value is the data value to send.
        """
        self.virtualWrite(channel, value, TYPE_TEMPERATURE, UNIT_KELVIN)

    def humidityWrite(self, channel, value):
        """Send a relative humidtys value to Cayenne.

        channel is the Cayenne channel to use.
        value is the data value to send.
        """
        self.virtualWrite(channel, value, TYPE_RELATIVE_HUMIDITY, UNIT_PERCENT)

    def luxWrite(self, channel, value):
        """Send a lux value to Cayenne.

        channel is the Cayenne channel to use.
        value is the data value to send.
        """
        self.virtualWrite(channel, value, TYPE_LUMINOSITY, UNIT_LUX)

    def pascalWrite(self, channel, value):
        """Send a pascal value to Cayenne.

        channel is the Cayenne channel to use.
        value is the data value to send.
        """
        self.virtualWrite(channel, value, TYPE_BAROMETRIC_PRESSURE,
                          UNIT_PASCAL)

    def hectoPascalWrite(self, channel, value):
        """Send a hectopascal value to Cayenne.

        channel is the Cayenne channel to use.
        value is the data value to send.
        """

        self.virtualWrite(channel, value, TYPE_BAROMETRIC_PRESSURE,
                          UNIT_HECTOPASCAL)

    def voltageWrite(self, channel, value):
        """Send a voltage value to Cayenne.

        channel is the Cayenne channel to use.
        value is the data value to send.
        """
        self.virtualWrite(channel, value, TYPE_VOLTAGE, UNIT_MILLIVOLTS)

    def digitalWrite(self, channel, value):
        """Send a voltage value to Cayenne.

        channel is the Cayenne channel to use.
        value is the data value to send.
        """
        self.virtualWrite(channel, value, TYPE_DIGITAL_SENSOR, UNIT_DIGITAL)

    def mqttPublish(self, topic, payload):
        """Publish a payload to a topic

        topic is the topic string.
        payload is the payload data.
        """
        self.log.info("PUB %s %s" % (topic, payload))
        self.client.publish(topic, payload)

    def getClient(self):
        return self.client

    def loop(self):
        """Process Cayenne messages.

        This should be called regularly to ensure Cayenne messages are sent and received.
        To be implemented later
        """
        self.client.check_msg()
        return

    def loop_forever(self):
        """Process Cayenne messages in a blocking loop that runs forever."""
        while True:
            self.client.wait_msg()
示例#12
0
def transmit(switch_cntrl,
             light1,
             light2,
             sw,
             topic,
             name="outlet_default",
             server="192.168.1.90",
             err_slp=100,
             err_rst=150):
    print("Starting MQTT transmitter...")

    #save the start time
    (syear, smonth, smday, shour, sminute, ssecond, sweekday,
     syearday) = utime.localtime()

    #configure switch pins
    outlet_switch = machine.Pin(sw, machine.Pin.OUT)
    outlet_light1 = machine.Pin(light1, machine.Pin.OUT)
    outlet_light2 = machine.Pin(light2, machine.Pin.OUT)
    outlet_cntrl = machine.Pin(switch_cntrl, machine.Pin.IN,
                               machine.Pin.PULL_UP)

    #set the outlet to the default state
    outlet_switch.off()
    outlet_light1.off()

    #flash the blue light so user has indication that outlet is working
    outlet_light2.on()
    time.sleep(.25)
    blink1()
    blink1()
    outlet_light1.on()

    #define the channels
    btopic = bytes(topic, 'utf-8')
    state_channel = btopic
    command_channel = btopic + b'/set'
    availability_channel = btopic + b'/available'
    debug_channel = 'debug'

    #set up udp socket
    c = MQTTClient(name, server)
    c.set_last_will(topic=availability_channel,
                    msg=b'offline',
                    retain=False,
                    qos=0)
    c.connect()
    print("Started!")

    #notify that you're available
    c.publish(availability_channel, b'online')

    def dbg_msg(name, msg):
        #debug messages
        payload = {}
        payload["outlet_name"] = name
        payload["message"] = msg
        a = ujson.dumps(payload)
        c.publish(debug_channel, a)

    dbg_msg(name, 'switch boot up')

    #status
    def status():
        (year, month, mday, hour, minute, second, weekday,
         yearday) = utime.localtime()

        print("")
        print("")
        print("Outlet v.0.5.0")
        print("{}/{}/{} {}:{}:{} | boot: {}/{}/{} {}:{}:{}".format(
            month, mday, year, hour, minute, second, smonth, smday, syear,
            shour, sminute, ssecond))
        print("Error Count: {}".format(str(error_cnt)))
        print("")
        print("Outlet status: " + str(outlet_switch.value()))
        print("Outlet name: " + name)
        print("Outlet topic: " + topic)

        dbg_msg(name, "Outlet status: " + str(outlet_switch.value()))

    #mqtt callback
    def monitor_cmds(topic, msg):
        if msg == b"ON":
            outlet_switch.on()
            try:
                c.publish(state_channel, b'ON')
                dbg_msg(name, 'switch commanded on')

            except:
                print("Error - Publish On!")
                rst_comm()
                error_cnt += 1
            outlet_light1.off()
            outlet_light2.on()

        elif msg == b"OFF":
            outlet_switch.off()
            try:
                c.publish(state_channel, b'OFF')
                dbg_msg(name, 'switch commanded off')
            except:
                print("Error - Publish Off!")
                rst_comm()
                error_cnt += 1
            outlet_light1.on()
            outlet_light2.on()

        #elif msg == b"schedule update":
        #elif msg == b"request schedule":
        #elif msg == b"schedule message":
        #elif msg == b"control selection":
        #elif msg == b"reboot":

    #phyisical button
    def btn_cntrl(p):
        time.sleep(1)
        if outlet_cntrl.value() == 0:
            if outlet_switch.value() == 0:
                monitor_cmds('', b'ON')
            else:
                monitor_cmds('', b'OFF')

        #debug messages
        dbg_msg(name, 'physical button pressed')

    def rst_comm():
        c.disconnect()
        c.connect()
        c.subscribe(command_channel)
        dbg_msg(name, 'device reset')

    #set interrupts
    c.set_callback(monitor_cmds)
    outlet_cntrl.irq(handler=btn_cntrl, trigger=outlet_cntrl.IRQ_FALLING)

    #subscribe to the command channel
    c.subscribe(command_channel)

    #wait
    error_cnt = 0
    while True:
        try:
            #check the command channel
            c.check_msg()
        except:
            print("Error - Check Message!")

            #reboot the connection
            rst_comm()
            error_cnt += 1

        #print status to the repl
        try:
            status()
        except:
            print("Error - Status")
            error_cnt += 1

        #watch error count, reset if limit exceeded
        if error_cnt == err_slp:
            time.sleep(15)
        elif error_cnt > err_rst:
            machine.reset()

        #Wait for a second
        time.sleep(1)

    c.disconnect()
    print('exiting...')
示例#13
0
class MqttClient:
    # User App of Hub SDK, subscribe and publish MQTT messages

    # http://www.hivemq.com/demos/websocket-client/
    MQTT_HOST = "broker.mqttdashboard.com"
    MQTT_PORT = 1883

    UNIQUE_ID = 'MC30AEA4CC1A40'
    DEFAULT_KEEPALIVE = const(60)
    KEEP_ALIVE_THRESHOLD = const(5)

    def __init__(self, callback=None):
        self.subscribeCallback = callback

        self.sn = self.UNIQUE_ID
        self.client = None
        self.topicSubOperation = "%s/operation" % (
            self.sn)  # same as: MC30AEA4CC1A40/operation
        self.topicPubUpdate = "%s/update" % (
            self.sn)  # same as: MC30AEA4CC1A40/update
        self.mqttLive = False
        log.info('MQTT init')

    def _clientInit(self):
        self.client = MQTTClient(client_id=self.sn,
                                 server=self.MQTT_HOST,
                                 port=self.MQTT_PORT,
                                 keepalive=DEFAULT_KEEPALIVE)

    def _clientConnect(self):
        log.debug('MQTT connecting...')
        try:
            self.client.connect()
            log.info('MQTT live!')
            self.mqttLive = True
            return True
        except Exception as e:
            log.exception(e, 'could not establish MQTT connection')
            return False

    def _subscribeTopic(self):
        try:
            self.client.set_callback(self._msgReceivedCallback
                                     )  # set a handler for incoming messages
            self.client.subscribe(topic=self.topicSubOperation, qos=0)
            log.info('subscribe [%s]', self.topicSubOperation)
        except Exception as e:
            log.exception(e, 'subscribe fail')

    def _resetPingTimer(self):
        self.pingCountdown = DEFAULT_KEEPALIVE

    def _ping(self):
        ''' do a MQTT ping before keepalive period expires '''
        self.pingCountdown -= 1
        if self.pingCountdown < KEEP_ALIVE_THRESHOLD:
            log.debug('mqtt ping...')
            self.client.ping()
            self._resetPingTimer()

    def _connectAttempt(self):
        if self._clientConnect():
            self._subscribeTopic()
            self._resetPingTimer()
            return True
        else:
            return False

    def _msgReceivedCallback(self, topic, msg):
        if self.subscribeCallback is not None:
            self.subscribeCallback(topic, msg)

    def mqttIsLive(self):
        return self.mqttLive

    def publishMsg(self, msg):
        try:
            topic = self.topicPubUpdate
            log.info("publish: topic[%s] msg[%s]", topic, msg)
            self.client.publish(topic=topic, msg=msg, qos=0)
        except Exception as e:
            log.exception(e, 'publish fail')

    async def taskMqttWorker(self):
        reconnectAttemptBackoff = 1  # don't try too hard, use backoff
        self._connectAttempt()
        while True:
            try:
                self.client.check_msg(
                )  # if there is a message, _msgReceivedCallback will be called
                self._ping()
                reconnectAttemptBackoff = 1
                await asyncio.sleep(1)
            except Exception as e:
                log.exception(e, 'MQTT check message problem')
                self.mqttLive = False
                if not self._connectAttempt():
                    reconnectAttemptBackoff *= 2  # don't retry too fast, this will abuse the server
                    if reconnectAttemptBackoff > 64:
                        reconnectAttemptBackoff = 64
                    log.debug('reconnect attempt backoff: %ds',
                              reconnectAttemptBackoff)
                    await asyncio.sleep(reconnectAttemptBackoff)

    def start(self):
        self._clientInit()
        asyncio.create_task(self.taskMqttWorker())
    # messages are being sent at a high rate
    led.value(not led.value())


# Blink the LED every 100ms to indicate we made it into the main.py file
for _ in range(10):
    time.sleep_ms(100)
    led.value(not led.value()) # Toggle the LED
    time.sleep_ms(100)

# Make sure the LED is off
led.high()

# define a time, because we only want to send every 1s but received as fast as possible
# last_time = time.time()

mqtt = MQTTClient(CLIENT_ID, HOST, port=PORT)
# Subscribed messages will be delivered to this callback
mqtt.set_callback(subscriction_callback)
mqtt.connect()
mqtt.subscribe(TOPIC)
print('Connected to {}, subscribed to {} topic.'.format(HOST, TOPIC))

try:
    while 1:
        #micropython.mem_info()
        mqtt.wait_msg()
finally:
    mqtt.disconnect()

示例#15
0
from machine import I2C, Pin
from esp8266_i2c_lcd import I2cLcd
from umqtt.simple import MQTTClient
import time

i2c = I2C(scl=Pin(5), sda=Pin(4))
lcd = I2cLcd(i2c, 0x27, 2, 16)

CONFIG = {
    "broker": "123.*.*.*",
    "client_id": b"NodeMCU",
    "topic": b"message",
}


def print_message(topic, msg):
    print("Received: " + msg.decode('UTF-8'))
    lcd.clear()
    lcd.putstr(msg.decode('UTF-8'))


client = MQTTClient(CONFIG['client_id'], CONFIG['broker'])
client.set_callback(print_message)
client.connect()
print("waiting for message")
client.subscribe(CONFIG['topic'])
while True:
    client.wait_msg()
    time.sleep(1)
client.disconnect()
示例#16
0
###################Connecting To Broker and Setting Clock on Device########################
from umqtt.simple import MQTTClient
client=MQTTClient("XYX17","192.168.0.10")#client ID, followed by broker addr
client.connect()

import ujson as json

def sub_cb(topic, msg):
    global time0
    print((topic,msg))
    timetemp=json.loads(msg)
    time0=timetemp['date']
    print('Time from the broker is: ', time0)
    
client.set_callback(sub_cb)
client.subscribe('esys/time')
print('Waiting for server time...')
client.wait_msg()

import machine
rtc=machine.RTC()
rtc.datetime((int(time0[0:4]),int(time0[5:7]),int(time0[8:10]),0,int(time0[11:13]),int(time0[14:16]),int(time0[17:19]),int(time0[20:22])))
print('Device time:', rtc.datetime())

##############Reading and Processing of Sensor Data###################################
def getvalues(reg_addr):
    data_l=i2c.readfrom_mem(24,reg_addr,1)
    data_h=i2c.readfrom_mem(24,reg_addr+1,1)
    value=(int(data_h[0])<<2)+(int(data_l[0])>>6)#10 Bit accuracy 
    if(0x80 & data_h[0]==0x80):
示例#17
0
            led.value(1)
            print("apagando luz")
    print("me llego por '{}' esto: {}".format(topic, msg))


# El nombre con el que nos registremos en el broker tiene que ser unico
# para eso podemos utilizar unique_id que nos devuelve la mac de nuestro dispositivo
id_cliente = hexlify(unique_id())

mqtt_server = "broker.hivemq.com"  # broker publico con el que podemos hacer pruebas
# tiene un cliente web en http://www.hivemq.com/demos/websocket-client/
client = MQTTClient(
    id_cliente,
    mqtt_server)  # si no decimos nada usa el puerto por defecto 1883
client.set_callback(
    mqtt_callback
)  # cuando entren mensajes por los topics a los que estamos suscritos, dispara el callback
client.connect()
client.subscribe(
    b'luz_salon_775')  # nos suscribimos a los topics que nos interese
client.subscribe(
    b'planta_baja/temperatura'
)  # notese que ponemos la b delante porque la libreria lo espera en formato byte array

proximo_envio = utime.ticks_ms(
) + TIEMPO_ENTRE_ENVIOS  # utilizamos este sistema para enviar mensajes cada 5 segundos

while True:
    client.check_msg(
    )  # comprueba mensajes, llamar frecuentemente pero no de continuo que nos da error
    # client.wait_msg()  # lo mismo que la linea anterior pero bloquea
示例#18
0
    print(topic, msg)
    #msg = str(msg)
    t = msg.decode('utf-8')  #convertendo a mensagem em byte para string

    if topic == b'semeca/leds':
        frequency = 5000
        led = PWM(Pin(5), frequency)
        pwm = int(msg)

        led.duty(pwm)
        c.publish(topic='semeca/led/intensidade', msg=msg)


sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('SEMECA-IOT', 'mecatronica')  #Conexão WIFI
print('Tentando conexao...')
while not sta_if.isconnected():  #Verifica莽茫o da conex茫o
    pass
print('Conectado!')

c = MQTTClient("Ledzinhos", '192.168.0.33', port=1883)  #broker
c.connect()
c.publish(topic='Conexao', msg=b"ESP8266 Conectada!")
c.publish(topic='Conexao', msg=b"Conexao OK")

c.set_callback(msg_callback)
c.subscribe('semeca/leds')
while True:
    c.wait_msg()
示例#19
0
文件: main.py 项目: snowcity007/SIoT
# 功能:订阅光线数据
# 实验:这个实验需要2个掌控板,一个发布光线数据一个订阅光线数据
#           需要先将公共文件中的Iot.py烧录到掌控板
#           订阅的掌控板,收到数据后,将光强信息显示在屏幕上
#           并且让RGB灯随着光强的变化而变化
#注意事项:这个实验需要2个掌控板,这是订阅端代码
#     1.本实验可用EasyIot物联网,用户需要注册EasyIot账号,添加
#     2.本实验可用Siot物联网,用户搭建Siot服务器:https://github.com/vvlink/SIoT/blob/master/source/setup/02_run.rst
#     产品和设备,并将产品设备信息更新到这个示例中
from mpython import *
from Iot import Iot
from umqtt.simple import MQTTClient
from machine import Timer
from machine import Pin
import machine
import time
import json
import network
WIFI_SSID = 'yourSSID'  #替换成你的WIFI热点名称
WIFI_PASSWORD = '******'  #替换成你的WIFI热点密码
IOT_SERVER = "server address"  #EASYIOT的服务器为iot.dfrobot.com.cn;Siot地址为用户搭建的服务器的ip地址,例如:192.168.0.100
IOT_PORT = 1883
IOT_ClientID = "your ClientID"  #替换成你的ClientID,可为空
IOT_UserName = "******"  #替换成你的UserName
IOT_PassWord = "******"  #替换成你的PassWord
IOT_subTopic = 'your SubTopic'  #如果是siot,自定义的topic中需要添加"/",例如:"abc/abc"
myIot = Iot(IOT_SERVER, IOT_UserName, IOT_ClientID, IOT_PassWord)
client = MQTTClient(myIot.client_id,
                    myIot.mqttserver,
                    port=IOT_PORT,
示例#20
0
class Lancha(object):
    DIR_MIN = 25
    DIR_MAX = 125
    DIR_CENTER = 75

    def __init__(self):
        self.wifi = None
        self.mqtt = None
        self.config = ujson.load(open("settings.json"))
        self.motor = Pin(4, Pin.OUT)
        self.servo = PWM(Pin(5), freq=50)
        self.current_dir = Lancha.DIR_CENTER

        # duty for servo is between 40 - 115
        # servo.duty(100)

    def wifi_connect(self):
        self.wifi = network.WLAN(network.STA_IF)
        self.wifi.active(True)
        if not self.wifi.isconnected():
            print("connect to {} {}".format(self.config["wifi"]["ssid"],
                                            self.config["wifi"]["pass"]))
            self.wifi.connect(self.config["wifi"]["ssid"],
                              self.config["wifi"]["pass"])
        while not self.wifi.isconnected():
            print("waiting for internet")
            time.sleep(1)
        return self.wifi.isconnected()

    def mqtt_connect(self):
        cfg = self.config["mqtt"]
        self.mqtt = MQTTClient(cfg["client_id"],
                               cfg["host"],
                               port=cfg["port"],
                               user=cfg["user"],
                               password=cfg["pass"])

        self.mqtt.set_callback(self.message_received)

        status = self.mqtt.connect()
        if status == 0:
            return True
        return False

    def mqtt_subscribe(self):
        cfg = self.config["mqtt"]
        self.mqtt.subscribe(cfg["topic"])

    def message_received(self, topic, msg):
        print("{}--> {}".format(topic, msg))

        payload = ujson.loads(msg)
        if payload.get("type") == "motor":
            val = payload.get("value")
            if val == 1:
                self.motor.on()
                print("prender motor")
            else:
                self.motor.off()
                print("apagar motor")
        elif payload.get("type") == "direction":
            val = payload.get("value")
            if val == -1:
                self.set_left()
            elif val == 1:
                self.set_right()
            elif val == 0:
                self.set_center()

    def set_center(self):
        self.servo.duty(Lancha.DIR_CENTER)

    def set_left(self):
        self.servo.duty(Lancha.DIR_MAX - 25)

    def set_right(self):
        self.servo.duty(Lancha.DIR_MIN + 25)

    def run(self):
        # Blocking wait for message
        #self.mqtt.wait_msg()
        print("RUN!")
        while True:
            self.mqtt.check_msg()
            time.sleep(.1)
示例#21
0
        return


def epoch():
    # Convert DS.datetime() to a format used by utime.mktime
    # (year, month, day, hour, minute, second, weekday, yearday)
    t = DS.datetime()
    wd = t.pop(3)
    t.append(wd)
    t.append(1)
    return utime.mktime(t)


connect_wifi()
c = MQTTClient(CLIENT, SERVER)
c.set_callback(on_message)
c.connect()
c.subscribe(TOPIC)
update_seconds = mqtt_seconds = epoch()

try:
    while True:
        secs = epoch()
        if secs - mqtt_seconds >= 60:
            # Check MQTT message every 60 seconds
            mqtt_seconds = secs
            c.check_msg()
        if secs - update_seconds >= 1:
            # Update LED intensity every second
            update_seconds = secs
            update_leds(ALARM_HOURS, ALARM_MINUTES, ALARM_SECONDS)
示例#22
0
            text = str(month) + "/" + str(day) + "/" + str(year)
            oled.fill(0)
            oled.text(text, 0, 0)
            oled.show()
        except:
            waiting = 1
            return
            pass
    elif (command == "time"):
        try:
            ntptime.settime()
            year, month, day, hour, minute, second, ms, dayinyear = time.localtime(
            )
            text = str(hour) + ":" + str(minute) + ":" + str(second)
            oled.fill(0)
            oled.text(text, 0, 0)
            oled.show()
        except:
            waiting = 1
            return
            pass


i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4))
oled = SSD1306_I2C(128, 64, i2c)
time.sleep(5)
client = MQTTClient(client_id="ESP8266-LCD", server="192.168.50.10")
client.set_callback(lcd_cb)
client.connect()
client.subscribe(b"lcd")
lcdLoop()
示例#23
0
def main():
    button = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_UP)
    orgid = "replace with your 6 character org id"
    token = "replace with your token"
    user = "******"
    # Make sure this matches up with the device type you configured through the IoT platform
    deviceType = "ESP8266"
    # Change to match your device Id
    deviceId = "pet2"

    server = '{}.messaging.internetofthings.ibmcloud.com'.format(orgid)
    clientId = 'd:{}:{}:{}'.format(orgid, deviceType, deviceId)
    try:
        client = MQTTClient(clientId,
                            server,
                            port=8883,
                            ssl=True,
                            user=user,
                            password=token)

    except:
        print('MQTT client setup error')

    try:
        client.set_callback(updatePet)

    except:
        print('MQTT callback error')

    pendingNotification = False
    reminded = False
    counter = 0
    while True:
        counter = counter + 1

        # every so many runs through the loop, connect to the MQTT broker to publish and check for messages
        # prevents repeated button press spam
        if counter >= 800:
            counter = 0
            if (reminded == False):
                remind('good')
                reminded = True
            client.connect()
            # non-blocking check for messages
            client.subscribe(b"iot-2/cmd/update-tracker/fmt/json")
            client.check_msg()
            client.disconnect()
            time.sleep(0.01)

            # send notification if button was pressed since last time
            if pendingNotification == True:
                print('connecting to MQTT broker...')
                client.connect()
                client.publish(b"iot-2/evt/habit/fmt/json",
                               b"{\"responded\":\"true\"}")
                pendingNotification = False
                print('disconnecting from MQTT broker')
                client.disconnect()

        # detect button presses
        firstButtonReading = button.value()
        time.sleep(0.01)
        secondButtonReading = button.value()
        if firstButtonReading and not secondButtonReading:
            # notification will be sent
            pendingNotification = True
            beHappy()
示例#24
0
文件: weiche.py 项目: jhon-p16/weiche
class WeicheMqtt:
    """
    MQTT Interface for all the weiche logic
    """
    def __init__(self, config, effectqueue, set_lights):
        self.config = config
        self.effectqueue = effectqueue
        self.set_lights = set_lights
        self.mqtt = None

    def connect(self):
        """
        Connect to the configured mqtt server, subscribe to topics and request
        an update
        """
        server = self.config.config('mqtt', 'server')
        server, port = server.split(":", 1)
        print("[*] Connecting to mqtt at %s port %s" % (server, port))
        self.mqtt = MQTTClient(self.config.client_id, server)
        self.mqtt.set_callback(self.mqtt_cb)
        self.mqtt.connect()

        default_topic = self.config.config('mqtt', 'default_topic')
        print("[*] Subscribing to topic (single msg)", default_topic)
        self.mqtt.subscribe(default_topic)

        mood_topic = self.config.config('mqtt', 'mood_topic')
        if mood_topic is None:
            print("[!] no mood topic set, ignoring")
        else:
            print("[*] Subscribing to topic (mood msg)", mood_topic)
            self.mqtt.subscribe(mood_topic)

        cue_topic = self.config.config('mqtt', 'queue_topic')
        print("[*] Subscribing to topic (cue)", cue_topic)
        self.mqtt.subscribe(cue_topic)

        # Request an update for the current light state
        self.mqtt.publish(b"/haspa/power/status",
                          json.dumps([self.config.client_id]))

        return self.mqtt.sock

    # Received messages from subscriptions will be delivered to this callback
    def mqtt_cb(self, topic, msg):
        """
        Branching for the different topics
        """
        try:
            msg = msg.decode('utf-8')
            jsondata = json.loads(msg)
        except:
            print("[!] Json error: ", msg)

        if isinstance(topic, bytes):
            topic = topic.decode()

        if topic == self.config.config('mqtt', 'default_topic'):
            self.mqtt_light_callback(jsondata)
        elif topic == self.config.config('mqtt', 'queue_topic'):
            self.mqtt_queue_callback(jsondata)
        elif topic == self.config.config('mqtt', 'mood_topic'):
            self.mqtt_mood_callback(jsondata)

    def mqtt_light_callback(self, jsondata):
        """
        Simple set lights targeted for this controller
        """
        if self.config.client_id not in jsondata.keys():
            return
        background_lights = jsondata[self.config.client_id]

        while len(background_lights) < 8:
            background_lights.append(0)

        self.set_lights(background_lights)

    def mqtt_mood_callback(self, jsondata):
        """
        Simple set lights, does not contain a target id
        """
        background_lights = jsondata

        if len(background_lights == 4):
            # double it up
            background_lights += background_lights

        while len(background_lights) < 8:
            background_lights.append(0)

        self.set_lights(background_lights)

    def mqtt_queue_callback(self, jsondata):
        """
        Set a lightshow targeted at this controller
        """
        if not isinstance(jsondata, dict):
            print(
                "[!] cue data has to be {\"ID\":[[time,[led1, led2, ...]], ...]"
            )
            return
        if self.config.client_id not in jsondata.keys():
            print("[!] Not meant for me")
            return

        print("[*] Received queue update. New cue:")
        self.effectqueue.update(jsondata[self.config.client_id])
        self.effectqueue.debug()

    @property
    def sock(self):
        """ Get the mqtt socket for poll() or select() """
        return self.mqtt.sock

    def check_msg(self):
        """ Proxy """
        return self.mqtt.check_msg()
示例#25
0
#Hardware Platform: FireBeetle-ESP32
#Result: input MQTTlibrary and remote controls LED by mqtt communication.
from umqtt.simple import MQTTClient
from machine import Pin
import network
import time
SSID = "yourSSID"
PASSWORD = "******"
led = Pin(2, Pin.OUT, value=0)
SERVER = "182.254.130.180"
CLIENT_ID = "yourClientID"
TOPIC = b"yourTOPIC"
username = '******'
password = '******'
state = 0
c = None

def sub_cb(topic, msg):
    global state
    print((topic, msg))
    if msg == b"on":
        led.value(1)
        state = 0
        print("1")
    elif msg == b"off":
        led.value(0)
        state = 1
        print("0")
    elif msg == b"toggle":
        # LED is inversed, so setting it to current state
示例#26
0
        jTemp = json.loads(result)
    except:
        waiting = 1
        return
        pass
    
    try:
        command = jTemp['command']
    except:
        waiting = 1
        return
        pass

def waveServo():
    global servo

    while(waiting):
        servo.duty(35)
        time.sleep(1)
        servo.duty(115)
        time.sleep(1)
        client.check_msg()

servo = machine.PWM(machine.Pin(4), freq=50)
servo.duty(75)
time.sleep(5)
client = MQTTClient(client_id="ESP8266-SERVO", server="192.168.50.10")
client.set_callback(servo_cb)
client.connect()
client.subscribe(b"servo")
servoLoop()
示例#27
0
class Device(object):
    def __init__(self,
                 name,
                 pin=None,
                 pwm=None,
                 freq=1000,
                 duty=1024,
                 irq=False,
                 read=None,
                 publish=None,
                 subscribe=None,
                 mqtt=None,
                 oneshot=False,
                 **kwargs):
        self.name = name
        self.kwargs = kwargs
        self.time = time.time()

        if type(mqtt) == tuple:
            try:
                kwargs = mqtt[1]
            except IndexError:
                kwargs = {}
            self.mqtt = MQTTClient(
                bytes('{0}/{1}'.format(MACHINE_ID, self.name), 'ascii'),
                bytes(mqtt[0], 'ascii'), **kwargs)
        else:
            self.mqtt = mqtt

        if not self.mqtt.connect(clean_session=True):
            print("Connected to MQTT as client {0}".format(
                self.mqtt.client_id))

        try:
            func_sample = kwargs.get('function_sample',
                                     'sample_{0}'.format(name))
            self.function_sample = getattr(self, func_sample)
        except:
            self.function_sample = None

        self.events = 0
        self.data = []

        if pin:
            self.pin_id = pin
            self.pin = machine.Pin(pin, machine.Pin.IN)
            self.pin_out = machine.Pin(pin,
                                       machine.Pin.OUT,
                                       value=self.pin.value)

        if pwm:
            self.pwm_id = pwm
            self.pwm = machine.PWM(machine.Pin(pwm), freq=freq, duty=duty)

        if read:
            self.read = read
            func_name = read.get('function', 'read_{0}'.format(name))
            self.function_read = getattr(self, func_name)
            if oneshot:
                self._callback_read()
            else:
                if read.get('irq'):
                    self.pin.irq(trigger=machine.Pin.IRQ_FALLING,
                                 handler=self._callback_read)
                else:
                    # Gather data in given interval if we are not going to use IRQ
                    self.timer_callback = machine.Timer(-1)
                    self.timer_callback.init(period=self.read['interval'] *
                                             1000,
                                             mode=machine.Timer.PERIODIC,
                                             callback=self._callback_read)

        if publish is not None:
            self.publish = publish
            self.publish['topic'] = bytes(
                publish.get(
                    'topic', "{0}/{1}".format(
                        publish.get('topic_base',
                                    "esp/{0}".format(MACHINE_ID)), self.name)),
                'ascii')
            if oneshot:
                self.publish_data()
            else:
                self.timer_publish = machine.Timer(-1)
                self.timer_publish.init(period=publish.get('interval', 30) *
                                        1000,
                                        mode=machine.Timer.PERIODIC,
                                        callback=self.publish_data)

        if subscribe is not None:
            self.subscribe = subscribe
            func_name = subscribe.get('function', 'write_{0}'.format(name))
            self.function_write = getattr(self, func_name)
            self.subscribe['topic'] = bytes(
                subscribe.get(
                    'topic', "{0}/{1}/control".format(
                        subscribe.get('topic_base',
                                      "esp/{0}".format(MACHINE_ID)),
                        self.name)), 'ascii')
            self.mqtt.set_callback(self._callback_subscribe)
            self.mqtt.subscribe(self.subscribe['topic'])
            if oneshot:
                self.subscribe_data()
            else:
                self.timer_subscribe = machine.Timer(-1)
                self.timer_subscribe.init(
                    period=subscribe.get('interval', 10) * 1000,
                    mode=machine.Timer.PERIODIC,
                    callback=self.subscribe_data)

    def _callback_read(self, *args, **kwargs):
        self.events += 1
        data = self.function_read(*args, **kwargs)
        if data:
            self.data.append(data)

    def _callback_subscribe(self, *args, **kwargs):
        print("{0}: received data over MQTT (args: {1}, kwargs: {2})".format(
            self.name, args, kwargs))
        self.events += 1
        data = self.function_write(*args, **kwargs)
        if data:
            self.data.append(data)
            self.publish_data(*args, **kwargs)

    def read_dht11(self, *args, **kwargs):
        import dht
        d = dht.DHT11(machine.Pin(self.pin_id))
        d.measure()
        print("{0}: {1}C, {2}%".format(self.name, d.temperature(),
                                       d.humidity()))
        return ({'temperature': d.temperature(), 'humidity': d.humidity()})

    def read_status(self, *args, **kwargs):
        print("{0}: status is {1}".format(self.name, self.pin.value()))
        return ({'value': self.pin.value()})

    def read_pwm(self, *args, **kwargs):
        return ({
            'freq': self.pwm.freq(),
            'duty': self.pwm.duty(),
        })

    def _fade_pwm(self, value, step=100, sleep=500):
        cur = self.pwm.duty()
        while cur != value:
            if value > cur:
                # We are putting duty higher
                new = cur + step
                if new > value:
                    self.pwm.duty(value)
                else:
                    self.pwm.duty(new)
            else:
                # Put duty lower
                new = cur - step
                if new < value:
                    self.pwm.duty(value)
                else:
                    self.pwm.duty(new)
            time.sleep_ms(sleep)
            cur = self.pwm.duty()

    def write_pwm(self, topic, data):
        param = json.loads(data)
        if param.get('freq'):
            print("{0}: setting pwm freq to {1}".format(
                self.name, param['freq']))
            self.pwm.freq(param['freq'])
        if param.get('duty'):
            print("{0}: setting pwm duty to {1}".format(
                self.name, param['duty']))
            if self.kwargs.get('fade'):
                self._fade_pwm(param['duty'],
                               step=self.kwargs['fade'].get('step', 100),
                               sleep=self.kwargs['fade'].get('sleep', 500))
            else:
                self.pwm.duty(param['duty'])
        return (param)

    def write_status(self, topic, value):
        self.pin_out.value(int(value))
        return ({'value': value})

    def toggle_status(self, *args, **kwargs):
        self.pin_out.value(0 if self.pin.value() else 1)
        return ({'value': self.pin.value()})

    def read_dht22(self, *args, **kwargs):
        import dht
        d = dht.DHT22(machine.Pin(self.pin_id))
        d.measure()
        print("{0}: {1}C, {2}%".format(self.name, d.temperature(),
                                       d.humidity()))
        return ({'temperature': d.temperature(), 'humidity': d.humidity()})

    def read_ds18x20(self, *args, **kwargs):
        import onewire
        import ds18x20
        ds = ds18x20.DS18X20(onewire.OneWire(self.pin))
        devs = ds.scan()
        ds.convert_temp()
        time.sleep_ms(750)

        data = {}
        i = 0
        for dev in devs:
            data['temperature{0}'.format(i)] = ds.read_temp(dev)
            print("{0}: {1}={2}C".format(self.name, i,
                                         data['temperature{0}'.format(i)]))
            i += 1

        return data

    def read_rpm(self, *args, **kwargs):
        pass

    def sample_rpm(self, *args, **kwargs):
        sample = time.time() - self.time
        print("{0}: {1} events in {2} seconds".format(self.name, self.events,
                                                      sample))
        return [{
            'rounds': self.events,
            'sample': sample,
            'rps': self.events / sample,
            'rpm': self.events / sample * 60,
        }]

    def reset(self):
        self.events = 0
        self.data = []
        self.time = time.time()

    def read_data(self, *args, **kwargs):
        irq_state = machine.disable_irq()

        if self.function_sample:
            data = self.function_sample()
        else:
            data = self.data

        ret = (self.events, data)
        self.reset()
        machine.enable_irq(irq_state)
        return ret

    def publish_data(self, *args, **kwargs):
        if self.publish.get('retain', False):
            self.mqtt.publish(self.publish['topic'],
                              bytes(json.dumps(self.read_data()[1][-1]),
                                    'ascii'),
                              retain=True)
        else:
            for dat in self.read_data()[1]:
                self.mqtt.publish(self.publish['topic'],
                                  bytes(json.dumps(dat), 'ascii'))
        print("Sent data to topic {0}".format(self.publish['topic']))

    def subscribe_data(self, *args, **kwargs):
        print("Reading data from topic {0}".format(self.name,
                                                   self.subscribe['topic']))
        self.mqtt.check_msg()
示例#28
0
文件: main.py 项目: Napat/uPyEsp
from umqtt.simple import MQTTClient
示例#29
0
# topics we recognize with their respective functions
subtopic = {
    b'led/set': set_state,
    b'led/dim': set_dim,
}


def handle_msg(topic, msg):
    # for debugging
    print("topic: ", topic, " msg: ", msg)

    if topic in subtopic:
        # call function associated with topic, passing message as parameter
        subtopic[topic](msg)
    else:
        print("topic not recognized")


######## MQTT Client: starting, connecting, and subscribing ##########

# start the MQTT client for this microcontroller
mq.set_callback(handle_msg)  # handle_msg() is called for ALL messages received
mq.connect()
mq.subscribe(b"led/#")

# wait for messages forever
# when one is received the function we passed to set_callback() will be run
while True:
    mq.wait_msg()
示例#30
0
# keep trying to connect to the wifi until we suceed
while not wlan.isconnected():
    np.fill((10, 0, 0))
    np.write()
    time.sleep_ms(200)
    np.fill((0, 0, 0))
    np.write()
    time.sleep_ms(300)

wlan.ifconfig()


def set_led(topic, msg):
    print("topic:'", topic, "' msg:'", msg, "'")
    np.fill((int(msg), int(msg), int(msg)))
    np.write()
# if topic == button or if topic == led
# do something with msg


# start the MQTT client for this microcontroller
mq = MQTTClient("neo", "192.168.0.23")
mq.set_callback(set_led)  # set_led will be called for ALL messages received
mq.connect()
mq.subscribe(b"led")  # specify the topic to subscribe to (led in this case)

# wait for messages forever
# when one is received the function we passed to set_callback() will be run
while True:
    mq.wait_msg()
示例#31
0
        mySensors.conf['Run_DS18B20'] = 'True'
        print('Scan i2c bus...')
        mySensors.sendi2c()
    elif msgDecoded == 'debugPrint1_on':
        client.publish('t', 'Debug on')
        print("Debug 1 turned on")
        mySensors.conf['debugPrint1'] = 'True'
    elif msgDecoded == 'debugPrint1_off':
        client.publish('t', 'Debug off')
        print("Debug 1 turned off")
        mySensors.conf['debugPrint1'] = 'False'
    elif msgDecoded == 'reboot':
        print("rebooting....")
        message = "rebooting"
        client.publish('t', message)
        utime.sleep_ms(500)
        mySensors.reboot()
    elif msgDecoded == 'saveConf':
        with open("config.py", "w") as f:
            f.write(ujson.dumps(mySensors.conf))
            print("conf saved")
        client.publish('t', 'Conf Saved')
    elif msgDecoded == 'printConfig':
        with open("config.py") as f:
            c = ujson.load(f)
            print(c)
        client.publish('t', 'Conf Saved')


client.set_callback(mqtt_sub_cb)
class AzureMQTT:
    def __init__(self,
                 connection_string: str,
                 policy_name=None,
                 expiry: int = 36000):
        self.params = dict(
            field.split('=', 1) for field in connection_string.split(';'))
        required_keys = ["HostName", "DeviceId", "SharedAccessKey"]
        if any(k not in self.params for k in required_keys):
            raise ValueError(
                "connection_string is invalid, should be in the following format:",
                "HostName=foo.bar;DeviceId=Fo0B4r;SharedAccessKey=Base64FooBar"
            )
        self.sas_token = generate_sas_token(self.params["HostName"],
                                            self.params["SharedAccessKey"],
                                            policy_name=policy_name,
                                            expiry=expiry)
        self.username = "******".format(
            host_name=self.params["HostName"],
            device_id=self.params["DeviceId"])
        self.password = self.sas_token

        self.mqtt_client = MQTTClient(client_id=self.params["DeviceId"],
                                      server=self.params["HostName"],
                                      user=self.username,
                                      password=self.password,
                                      ssl=True)
        self._default_subscribe_string = "devices/{device_id}/messages/devicebound/#".format(
            device_id=self.params["DeviceId"])

    def _default_subscribe(self):
        subscription_string = "devices/{device_id}/messages/devicebound/#".format(
            device_id=self.params["DeviceId"])
        self.mqtt_client.subscribe(subscription_string)

    def setup(self,
              callback=_default_call_back,
              subscribe_string: str = "default"):
        """
        An easy way to connect, set the callback, and subscribe to messages.
        :return:
        """
        self._connect()
        self.mqtt_client.set_callback(callback)
        if subscribe_string == "default":
            self.mqtt_client.subscribe(self._default_subscribe_string)
        else:
            self.mqtt_client.subscribe(subscribe_string)

    def _connect(self):
        """
        A relay to self.mqtt_client.connect(), but with errors that return usable info that doesn't require the spec
        sheet to figure out what's going on.
        :return:
        """
        try:
            self.mqtt_client.connect()
        except MQTTException as e:
            error_num = int(e.args[0])
            if error_num == 1:
                raise MQTTException(
                    "1: Server does not support level of MQTT protocol requested by the client."
                )
            elif error_num == 2:
                raise MQTTException(
                    "2: The Client identifier is correct UTF-8 but not allowed by the Server."
                )
            elif error_num == 3:
                raise MQTTException(
                    "3: The Network Connection has been made but the MQTT service is unavailable."
                )
            elif error_num == 4:
                raise MQTTException(
                    "4: The data in the user name or password is malformed.")
            elif error_num == 5:
                raise MQTTException(
                    "5: The client is not authorized to connect.")
            elif error_num >= 6:
                raise MQTTException(
                    str(error_num) + ":",
                    "The server reported an error not specified in the MQTT spec as of v3.1.1"
                )

    def send(self, property_name: str, property_value: str):
        topic_string = "devices/{device_id}/messages/events/".format(
            device_id=self.params["DeviceId"])
        payload_string = "{%s=%s}" % (property_name, property_value)
        self.mqtt_client.publish(topic=topic_string, msg=payload_string)

    def wait_msg(self):
        self.mqtt_client.wait_msg()

    def check_msg(self):
        self.mqtt_client.check_msg()

    def print(self):
        print("Host Name:        ", self.params["HostName"])
        print("Device ID:        ", self.params["DeviceId"])
        print("Shared Access Key:", self.params["SharedAccessKey"])
        print("SAS Token:        ", self.sas_token)
        print("Username:         "******"Password:         ", self.password)
示例#33
0
class MQTTClientWrapper:

    def __init__(self, config):

        self.server = config.MQTT_SERVER
        self.port = config.MQTT_PORT
        self.mqtt_client = MQTTClient(
            client_id=config.MQTT_CLIENT_ID,
            server=self.server,
            port=self.port,
            user=config.MQTT_USER,
            password=config.MQTT_PASSWORD,
            keepalive=config.MQTT_KEEPALIVE,
            ssl=config.MQTT_SSL,
            ssl_params=config.MQTT_SSL_PARAMS,
        )
        self.mqtt_client.set_callback(self._process_incoming_msgs)
        self.callbacks = {}
        self.connected = False
        self.max_retries = MQTT_MAX_RETRIES

    def connect(self):
        attempt = 1
        while attempt <= self.max_retries:
            print('connecting to mosquitto server "{}:{}" (attempt {})...'
                  .format(self.server, self.port,
                          attempt), end='')

            try:
                res = self.mqtt_client.connect()
                if res == 0:
                    print('done')
                    break
                else:
                    print('error {}'.format(res))
                    attempt += 1

            except OSError:
                print('error')
                attempt += 1
        else:
            self.connected = False
            raise MQTTConnectionError()

        self.connected = True

    def disconnect(self):
        self.mqtt_client.disconnect()

    def publish(self, topic, msg, qos=0, retain=False):
        print('publishing topic {}: {}...'.format(topic, msg), end='')
        self.mqtt_client.publish(topic, msg, qos, retain)
        print('done')

    def subscribe(self, topic, callback):
        self.callbacks[topic] = callback
        self.mqtt_client.subscribe(topic)

    def _process_incoming_msgs(self, topic, msg):
        topic = topic.decode()
        msg = msg.decode()
        callback = self.callbacks.get(topic)
        if callback is not None:
            callback(topic, msg)

    def wait_msg(self):
        return self.mqtt_client.wait_msg()

    def check_msg(self):
        return self.mqtt_client.check_msg()

    def ping(self):
        return self.mqtt_client.ping()
示例#34
0
文件: main.py 项目: mampersat/minions
""" Main control logic

Initialize neopixels
Connect to network
Register Callbacks
start main loop
"""

allOff()
# startUpAllOn()
# night_rider_2()
# bin_walk()
# bin_walk_3()
hour_glass()

client.set_callback(gotMessage)

s = network.WLAN(network.STA_IF)
while not s.isconnected():
    # s.connect('ShArVa')
    print("Network not connected - sleeping")
    time.sleep(1)

print(s.ifconfig())

connected = False
while not connected:
    try:
        print("Connecting")
        client.connect()
    except:
示例#35
0
WIFI_PASSWORD="******"   #insert your wifi password

SERVER="IP_OF_MOSQUITTO_SERVER"
TOPIC=b"AFNOG19"
PAYLOAD=b"Welcome to the AFNOG-2019 workshop"

def cmdCallback(topic,payload):
    print(topic,payload)
    
wlan=network.WLAN(network.STA_IF)
wlan.active(True)

wlan.disconnect()

print("Trying to connect to %s"%SSID)
wlan.connect(SSID,WIFI_PASSWORD)
        
while(wlan.ifconfig()[0]=='0.0.0.0'):
    time.sleep(1)
print("Successfully connected to WiFi network")
print('network config:', wlan.ifconfig())

c = MQTTClient("umqtt_client", SERVER)
c.connect()

c.set_callback(cmdCallback)
c.subscribe("AFNOG19")

while True:
    c.wait_msg()