Exemplo n.º 1
0
class DoorAlarm(object):

    def __init__(self):
        self.config = None
        self.p0 = machine.Pin(2, machine.Pin.OUT)

    def load_config(self):
        with open('cfg.json', 'r') as cfg:
            self.config = ujson.load(cfg)

    def connect_wifi(self):
        ap_if = network.WLAN(network.AP_IF)
        ap_if.active(False)

        sta_if = network.WLAN(network.STA_IF)
        sta_if.active(True)

        if sta_if.isconnected():
            sta_if.disconnect()

        sta_if.connect(self.config['ssid'], self.config['passwd'])

        for _ in range(20):
            time.sleep(1)

            if sta_if.isconnected():
                return

        print('Unable to connect to AP: {}'.format(ssid))
        sys.exit(1)

    def mqtt_callback(self, topic, msg):
        self.p0.value(not self.p0.value())

    def mqtt_subscribe(self):
        client_id = b'tom_' + ubinascii.hexlify(machine.unique_id())
        self.mqtt = MQTTClient(client_id, self.config['host'],
                               port=int(self.config['port']))

        self.mqtt.set_callback(self.mqtt_callback)
        self.mqtt.connect()
        self.mqtt.subscribe(self.config['topic'])
import time
from umqtt.robust import MQTTClient


def sub_cb(topic, msg):
    print((topic, msg))


c = MQTTClient("umqtt_client", "localhost")
# Print diagnostic messages when retries/reconnects happens
c.DEBUG = True
c.set_callback(sub_cb)
# Connect to server, requesting not to clean session for this
# client. If there was no existing session (False return value
# from connect() method), we perform the initial setup of client
# session - subscribe to needed topics. Afterwards, these
# subscriptions will be stored server-side, and will be persistent,
# (as we use clean_session=False).
#
# There can be a problem when a session for a given client exists,
# but doesn't have subscriptions a particular application expects.
# In this case, a session needs to be cleaned first. See
# example_reset_session.py for an obvious way how to do that.
#
# In an actual application, it's up to its developer how to
# manage these issues. One extreme is to have external "provisioning"
# phase, where initial session setup, and any further management of
# a session, is done by external tools. This allows to save resources
# on a small embedded device. Another extreme is to have an application
# to perform auto-setup (e.g., clean session, then re-create session
# on each restart). This example shows mid-line between these 2
Exemplo n.º 3
0
#    logtime=time.localtime()
#    log.write("{}.{}.{} {}:{}:{} - {}\n".format(logtime[2],logtime[1],logtime[0],logtime[3]+TZ,logtime[4],logtime[5],logentry))

# Configure MQTT
logentry = "Configuring MQTT."
logtime = time.localtime()
log.write("{}.{}.{} {}:{}:{} - {}\n".format(logtime[2], logtime[1], logtime[0],
                                            logtime[3] + TZ, logtime[4],
                                            logtime[5], logentry))
c = MQTTClient(client_id=mqtt_config['mqtt_client'],
               server=mqtt_config['mqtt_broker'],
               user=mqtt_config['mqtt_user'],
               password=mqtt_config['mqtt_pwd'],
               port=mqtt_config['mqtt_port'])
c.DEBUG = True
c.set_callback(sub_cb)
wdt.feed()
c.connect()
wdt.feed()
print(gw_config['gw_topic'] + '/' + gw_config['gw_id'])
# LoRaMQTTGateway is subscribed to topic gw_topic/gw_id and its subtopics
c.subscribe(gw_config['gw_topic'] + '/' + gw_config['gw_id'])
c.subscribe(gw_config['gw_topic'] + '/' + gw_config['gw_id'] + '/#')
print("MQTT broker {} connected!".format(mqtt_config['mqtt_broker']))
logentry = "MQTT broker {} connected!".format(mqtt_config['mqtt_broker'])
logtime = time.localtime()
log.write("{}.{}.{} {}:{}:{} - {}\n".format(logtime[2], logtime[1], logtime[0],
                                            logtime[3] + TZ, logtime[4],
                                            logtime[5], logentry))

Exemplo n.º 4
0
    topic = TOPIC_BASE + 'cmd/%d' % channel
    print("Subscribing to topic %s, please wait 5 s" % topic)
    time.sleep(0.5)
    c.subscribe(topic)
    print("Subscribe sent")


# switch the LED off, it is too bright!

neoPixel[0] = (red, green, blue)
neoPixel.write()

connectWifi(SSID, PASSWORD)
server = SERVER
print("Connecting to myDevices MQTT broker")
c = MQTTClient(CLIENT_ID, server, 0, username, password)
print("Registering callback")
c.set_callback(ledUpdate)
if not c.connect(clean_session=False):
    print("New session being set up")
    subscribeCayenne(2)
    subscribeCayenne(3)
    subscribeCayenne(4)

while True:
    try:
        print("Wait for mgs")
        c.wait_msg()
    except OSError:
        pass
Exemplo n.º 5
0
def send_state():
    client = MQTTClient('state', SERVER)
    client.connect()
    client.set_callback(on_message)
    client.publish(state, '2')
    freeHeap = float(str(msg,'utf-8'))
    print("free heap size = {} bytes".format(freeHeap))
  
randomNum = int.from_bytes(os.urandom(3), 'little')
myMqttClient = bytes("client"+str(randomNum), 'utf-8')

THINGSPEAK_URL = b"mqtt.thingspeak.com" 
THINGSPEAK_USER_ID = b'ID_CANAL'
THINGSPEAK_MQTT_API_KEY = b'CHAVE_API_MQTT'
client = MQTTClient(client_id=myMqttClient, 
                    server=THINGSPEAK_URL, 
                    user=THINGSPEAK_USER_ID, 
                    password=THINGSPEAK_MQTT_API_KEY, 
                    ssl=False)

client.set_callback(cb)
try:            
    client.connect()
except Exception as e:
    print('could not connect to MQTT server {}{}'.format(type(e).__name__, e))
    sys.exit()

THINGSPEAK_CHANNEL_ID = b'ID_DO_CANAL'
THINGSPEAK_CHANNEL_WRITE_API_KEY = b'CHAVE_WRITE_DO_CANAL'
subscribeTopic = bytes("channels/{:s}/subscribe/fields/field1/{:s}".format(THINGSPEAK_CHANNEL_ID, THINGSPEAK_CHANNEL_READ_API_KEY), 'utf-8')  
client.subscribe(subscribeTopic)

while True:
    try:
        client.wait_msg()
    except KeyboardInterrupt:
Exemplo n.º 7
0
# Define a namespace for all messages
MQTT_Topic_Status = 'JorgePe/Status'
MQTT_Topic_Motor = 'JorgePe/Motor'


# callback message to process any new message appearing at the subscribed
# topics
def getmessages(topic, msg):
    if topic == MQTT_Topic_Status.encode():
        brick.display.text(str(msg.decode()))
    elif topic == MQTT_Topic_Motor.encode():
        brick.display.text(str(msg.decode()))
        motor.run_target(180, int(msg.decode()))


motor.reset_angle(0)

client = MQTTClient(MQTT_ClientID, MQTT_Broker)
client.connect()

client.publish(MQTT_Topic_Status, MQTT_ClientID + ' Started')
client.set_callback(getmessages)
client.subscribe(MQTT_Topic_Status)
client.subscribe(MQTT_Topic_Motor)
client.publish(MQTT_Topic_Status, MQTT_ClientID + ' Listening')

while True:
    client.check_msg()
    time.sleep(0.1)
Exemplo n.º 8
0
iw.oled.show()

# Connect to MQTT broker
iw.oled.text("MQTT connecting",0,10)
iw.oled.show()
mqtt = MQTTClient("clientId-XXXXXXXXXXXXXXXXXXXXXXX","broker.mqttdashboard.com")  
mqtt.connect()                                       
iw.oled.text("MQTT connected",0,10)
iw.oled.show()

def sub_cb(topic,msg):             
  if topic == b"krujeen/data/temp": 
    iw.oled.fill(0)             
    iw.oled.text(msg,0,0)       
    iw.oled.show()
mqtt.set_callback(sub_cb)           
mqtt.subscribe("krujeen/data/#")  


# Config BLYNK
BLYNK_AUTH = 'XXXXXXXXXXXXXXXXXXXXXXX'
blynk = BlynkLib.Blynk(BLYNK_AUTH)

def on_connect():
  print("connected")
blynk.on_connect(on_connect)

def on_disconnect():
  print("disconnected")
blynk.on_disconnect(on_disconnect)
Exemplo n.º 9
0
class MQTT:
    def __init__(self, ssid, pswd):
        self.WIFI_SSID = ssid
        self.WIFI_PSWD = pswd

        self.subLoopRunning = False

        # create a random MQTT clientID
        random_num = int.from_bytes(os.urandom(3), 'little')
        self.mqtt_client_id = bytes('client_' + str(random_num), 'utf-8')
        #email = [email protected] password db4password
        self.ADAFRUIT_IO_URL = b'io.adafruit.com'
        self.ADAFRUIT_USERNAME = b'db4g5'
        self.ADAFRUIT_IO_KEY = Key()

        self.connect()

    def __del__(self):
        self.subLoopRunning = False

    def connect(self):
        # turn off the WiFi Access Point
        ap_if = network.WLAN(network.AP_IF)
        ap_if.active(False)

        # connect the device to the WiFi network
        wifi = network.WLAN(network.STA_IF)
        wifi.active(True)
        wifi.connect(self.WIFI_SSID, self.WIFI_PSWD)

        attempt_count = 0
        while not wifi.isconnected() and attempt_count < 20:
            attempt_count += 1
            time.sleep(1)

        if attempt_count == 20:
            print('could not connect to the WiFi network')
            sys.exit()

        self.client = MQTTClient(client_id=self.mqtt_client_id,
                                 server=self.ADAFRUIT_IO_URL,
                                 user=self.ADAFRUIT_USERNAME,
                                 password=self.ADAFRUIT_IO_KEY,
                                 ssl=False)

        try:
            self.client.connect()
        except Exception as e:
            print('could not connect to MQTT server {}{}'.format(
                type(e).__name__, e))
            sys.exit()

    # used to publish new data to a certain topic
    def publish(self, topic, value):
        mqtt_feedname = bytes(
            '{:s}/feeds/{:s}'.format(self.ADAFRUIT_USERNAME, topic), 'utf-8')
        try:
            self.client.publish(mqtt_feedname,
                                bytes(str(value), 'utf-8'),
                                qos=0)
        except Exception:
            self.connect()

    # used to poll client subscriptions
    def __sub_loop(self):
        while self.subLoopRunning:
            try:
                self.client.check_msg()
                time.sleep(2)
            except Exception:
                self.connect()

    # run only once with custom function func(topic, msg)
    def setCallback(self, cb):
        self.client.set_callback(cb)

    # add a subscription
    def subscribe(self, topic):
        mqtt_feedname = bytes(
            '{:s}/feeds/{:s}'.format(self.ADAFRUIT_USERNAME, topic), 'utf-8')
        self.client.subscribe(mqtt_feedname)
        if self.subLoopRunning == False:
            self.subLoopRunning = True
            _thread.start_new_thread(self.__sub_loop, ())
Exemplo n.º 10
0
    certf = f.read()
print(certf)

with open(key, 'rb') as f:
    keyf = f.read()
print(keyf)

with open(root, 'rb') as f:
    rootf = f.read()
print(rootf)

time.sleep(1)

conn = MQTTClient(client_id=TOPIC,
                  server=HOST,
                  port=8883,
                  ssl=True,
                  ssl_params={
                      "cert": certf,
                      "key": keyf
                  })
conn.set_callback(cb)
conn.connect()
conn.subscribe(TOPIC)

msg = 'mensaje'

while True:
    connection.publish(topic=TOPIC, msg=msg, qos=0)
    sleep(2)
Exemplo n.º 11
0
        client.publish(b'SessionID', ca.sessionID)

    except OSError as e:
        restart_and_reconnect()


# Main Function
do_connect()
ca = CryptAes()

client = MQTTClient(client_id=client_id,
                    server=mqtt_server,
                    port=port,
                    user=username,
                    password=password)
client.set_callback(sub_cb)
client.connect()
client.subscribe(b'Sensor_Data')
print("Connected to MQTT Broker")

#hard_timer1.init(period=1000, mode=machine.Timer.PERIODIC, callback=hard_handleInterrupt1)
client.publish(b'SessionID', ca.sessionID)
print("published message")
ticks_1 = utime.ticks_ms()

while True:
    new_message = client.check_msg()
    time.sleep_us(1000)
    if mail_flag == 1:
        mail_flag = 0
        result = ca.verify_hmac(json_message)
Exemplo n.º 12
0
        print('unknown command')
        return

    if payload['type'] == 'pinstatus':
        send_pin_status()
    elif payload['type'] == 'changepin':
        if 'data' in payload and type(payload['data']) == dict:
            pins_changed = 0
            for pin in payload['data']:
                if type(pin) == str and not str.isdigit(pin): continue
                ipin = int(pin)
                if ipin < len(digital_out_pins):
                    pin_val = int(payload['data'][pin])
                    machine.Pin(digital_out_pins[ipin],
                                machine.Pin.OUT).value(pin_val)
                    pins_changed += 1
            if pins_changed: send_pin_status()


send_pin_status()
client.set_callback(on_mqtt_msg)
channel = '{}/{}'.format('/hydroots/server', machineid)
client.subscribe(channel)
print('subscribed', channel)

if __name__ == '__main__':
    while True:
        print('looping')
        check_data_send()
        client.check_msg()
        time.sleep(1)
Exemplo n.º 13
0
def onMessage_local(topic, msg):
    m=loads(msg)
    print(m)
    config["config_sync"] = m["config_sync"]
    config["time_interval"] = m["time_interval"]*60
    config["local"] = m["local"]
    config["cloud"] = m["cloud"]
    config["buzzer"] = m["buzzer"]
    config["msg_alert"] = m["msg_alert"]
    config["powersave"] = m["powersave"]
    config["auto_freq"] = m["auto_freq"]
    config["max_freq"] = m["max_freq"]
    

mqtt_local.set_callback(onMessage_local)
mqtt_cloud.set_callback(onMessage_cloud)

try:
    mqtt_local.subscribe("smartgiger",qos=0)
    print("waiting for msg...")
    led.color(500, 700)
    mqtt_local.check_msg()
    
except:
    print("local subscribe faild")
    led.color(r=1023,g=0)
timer = ticks_ms()


async def geiger_count():