コード例 #1
0
def connectMQTT():
    global sta_if, c
    c = MQTTClient(CLIENT_ID, SERVER, 1883, username, password)
    c.DEBUG = True
    c.set_callback(sub_cb)
    c.connect()
    #close_all()
    cur_state = json.dumps(get_states())
    c.publish(TOPIC, cur_state, retain=True)
    print(cur_state)
    sub_msg()
コード例 #2
0
def connect_and_subscribe():
    global client_id, mqtt_server, topic_sub, mqtt_pw, mqtt_username
    client = MQTTClient(client_id, mqtt_server, 0, mqtt_username, mqtt_pw,
                        keepalive_interval, False, {})
    print(
        'About to try to connect to %s MQTT broker, subscribed to %s password %s username'
        % (mqtt_server, mqtt_pw, mqtt_username))
    client.DEBUG = True
    client.set_callback(sub_cb)
    if not client.connect(clean_session=False):
        print("New session being set up")
        client.subscribe(topic_sub)
    else:
        print('do not set up new session, reconnect to existing one...')
        client.subscribe(topic_sub)
    print('Connected to %s MQTT broker, subscribed to %s topic' %
          (mqtt_server, topic_sub))
    return client
コード例 #3
0
def setMQTT(callback):
    global info
    try:
        info = readFile(MQTT_FILENAME)
        client = MQTTClient(client_id=ID, server=info['host'],
                            user=info['username'], password=info['password'], port=int(info['port']))
        client.set_last_will(topic=info['topic'], msg=info['lastWillMsg'])
        # Print diagnostic messages when retries/reconnects happens
        client.DEBUG = (info['consoleVerbose'] == "True")
        client.set_callback(callback)
        return client
    except OSError:
        print("MQTT config file does not exist")
コード例 #4
0
#https://help.ubidots.com/developer-guides/ubidots-mqtt-broker

import network
from robust import MQTTClient  #no esta incluida en el firmware para el esp32, deben ser agregados los scripts de mqtt
import time

#conexion wifi
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect("SSID", "PASS")
time.sleep(5)

#se debe especificar el token de acuerdo a la cuenta de ubidots y el clientid con el que se subscribira el esp
ubidotsToken = "ubiotstoken"
clientID = "clientid"
topic = b"/v1.6/devices/esp32lora"  #el topic define a que device en especifico es que se va a subir datos
#b"/v1.6/devices/{NOMBRE_DISPOSITIVO}" en el que NOMBRE_DISPOSITIVO es quien
#define entre los devices creados al cual se quiere subir el dato

client = MQTTClient(clientID,
                    "mqtt://things.ubidots.com",
                    1883,
                    user=ubidotsToken,
                    password=ubidotsToken)  #creacion de objeto
client.connect()  #conexion a ubidots

#ejemplo de uso del metodo de publicacion
temp, humid = msg.split('|')
msg = b'{"temp":%s, "humid":%s}' % (temp, humid)
print(msg)
client.publish(topic, msg)
コード例 #5
0
ファイル: main.py プロジェクト: fossabot/LoRaTracker
# start new log file with headers
with open(log_filename, 'a') as Log_file:
    Log_file.write(str(rtc.now()) + '\n')
    Log_file.write('remote_ID,GPSFix,latitude,longitude,voltage,rssi\n')

if use_WebServer and network_OK:
    print ("Starting Webserver")
    routes = WWW_routes()
    mws = MicroWebSrv(routeHandlers=routes, webPath="/sd") # TCP port 80 and files in /sd
    gc.collect()
    mws.Start()
    gc.collect()

if use_MQTT and internet_OK:
    print ('Starting MQTT')
    mqtt = MQTTClient(my_ID, "io.adafruit.com",user="******", password="******", port=1883)
    mqtt.set_callback(mqtt_callback)
    mqtt.connect()
    mqtt.subscribe(topic="agmatthews/feeds/LORAtest")

print ("Starting Lora")
lora = LoRa(mode=LoRa.LORA, region=LoRa.AU915)
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setblocking(False)

print ("Waiting for data")

while True:
    # feed the watch dog timer
    wdt.feed()
    # update the status LED
コード例 #6
0
ファイル: main.py プロジェクト: knoby/serial2mqtt
SERIAL_BAUD_RATE = 9600

##########################

uart = UART(0,
            baudrate=SERIAL_BAUD_RATE,
            timeout=100,
            timeout_char=50,
            rxbuf=128)

# wait for connection
wifi = network.WLAN(network.STA_IF)
while not wifi.isconnected():
    time.sleep(1)

client = MQTTClient(MQTT_Client_Name, MQTT_Server_IP)
client.connect(clean_session=True)

# Counter test
counter = 1
while 1:

    # Read from Serial
    while 1:
        line = uart.readline()
        if line == None:
            break

        # Eval the line
        line = line.strip()
        if not line.startswith("--MQTT--"):
コード例 #7
0

def loadConfigs():
    global cnf
    f = open('config.json')
    cnf = json.loads(f.read())
    f.close()


loadConfigs()

sta_if = network.WLAN(network.STA_IF)
broker = MQTTClient(cnf["mqtt"]["id"],
                    cnf["mqtt"]["host"],
                    port=cnf["mqtt"]["port"],
                    user=cnf["mqtt"]["user"],
                    password=cnf["mqtt"]["pass"],
                    keepalive=cnf["mqtt"]["keepalive"],
                    ssl=cnf["mqtt"]["ssl"])
now = ticks_ms()
start = ticks_ms()
heartbeat = ticks_ms()

nextion.connect(cnf)

nextion.dims(100)


def connectToWifi():
    global sta_if
    global cnf
コード例 #8
0
from lora import LoRa


def cb(msg):
    temp, humid = msg.split('|')
    msg = b'{"temp":%s, "humid":%s}' % (temp, humid)
    print(msg)
    client.publish(b"/v1.6/devices/esp32lora", msg)


sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.scan()  # Scan for available access points
sta_if.connect("SSID", "PASS")  # Connect to an AP
sta_if.isconnected()
time.sleep(5)

ubidotsToken = "ubiotstoken"
clientID = "clientid"

client = MQTTClient(clientID,
                    "industrial.api.ubidots.com",
                    1883,
                    user=ubidotsToken,
                    password=ubidotsToken)
client.connect()

lora = LoRa()
lora.set_callback()
lora.wait_msg()
コード例 #9
0
def getCommand():
    #ADAFRUIT_IO_DETAILS
    ADAFRUIT_IO_URL = b'io.adafruit.com'
    ADAFRUIT_USERNAME = b'ADAFRUIT USERNAME'  #Enter your UserName
    ADAFRUIT_IO_KEY = b'ADAFRUIT AIO KEY'  #Enter AIO key
    ADAFRUIT_IO_FEEDNAME = b'IO FEEDNAME'  #Enter IO FEEDNAME

    #CREATING OBJECT FOR MQTTClient Module
    client = MQTTClient(client_id=mqtt_client_id,
                        server=ADAFRUIT_IO_URL,
                        user=ADAFRUIT_USERNAME,
                        password=ADAFRUIT_IO_KEY,
                        ssl=False)

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

    #Setting feedname
    mqtt_feedname = bytes(
        '{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAFRUIT_IO_FEEDNAME),
        'utf-8')
    #setting a callback function for client object
    client.set_callback(cb)
    print('callback set')

    #Subscribing For the Latest updated feed data
    client.subscribe(mqtt_feedname)
    print('Subscribed for data')
    mqtt_feedname_get = bytes('{:s}/get'.format(mqtt_feedname), 'utf-8')
    client.publish(mqtt_feedname_get, '\0')

    # wait until data has been Published to the Adafruit IO feed
    msg = client.wait_msg()
    Command1 = str(msg, 'utf-8')
    client.disconnect()
    #returning the command to the My_BOT Module
    return Command1
コード例 #10
0
    #configuracion del sensor de temperatura humedad
    d = dht.DHT11(machine.Pin(0))

    #configuracion del i2c para sensor de luz
    Pin_sda = machine.Pin(5)
    Pin_scl = machine.Pin(4)
    i2c = machine.I2C(freq=400000, sda=Pin_sda, scl=Pin_scl)
    i2c.writeto(35, b'\x10')
    ina = INA226(i2c, addr=0x40)
    ina.set_calibration_custom(calValue=512, config=0x4127)

    #configuracion de MQTT
    c = MQTTClient("sensor" + str(Nsens),
                   server=url,
                   port=1883,
                   user=user,
                   password=pwrd,
                   keepalive=30)
    c.set_callback(sub_cb)
    c.connect()
    #for i in range(0,5):
    #    try:
    #        c.connect()
    #        i=5
    #    except:
    #        print("fallo en conexion MQTT")

    #loop principal

    #configuracion timer
    tim = machine.Timer(1)
コード例 #11
0

'''
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SETTING THE CALLBACKS AND INITIALIZING CLIENT
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'''

# Create an MQTT client instance.

random_num = int.from_bytes(os.urandom(3), 'little')
mqtt_client_id = bytes('client_' + str(random_num), 'utf-8')

client = MQTTClient(client_id=mqtt_client_id,
                    server=ADAFRUIT_IO_URL,
                    user=ADAFRUIT_IO_USERNAME,
                    password=ADAFRUIT_IO_KEY,
                    ssl=False)

random_num = int.from_bytes(os.urandom(3), 'little')
mqtt_client_id = bytes('client_' + str(random_num), 'utf-8')

client_P = MQTTClient(client_id=mqtt_client_id,
                      server=ADAFRUIT_IO_URL,
                      user=ADAFRUIT_IO_USERNAME,
                      password=ADAFRUIT_IO_KEY,
                      ssl=False)

random_num = int.from_bytes(os.urandom(3), 'little')
mqtt_client_id = bytes('client_' + str(random_num), 'utf-8')
コード例 #12
0
ファイル: main.py プロジェクト: royedfa1125/Hotwave
import machine
import os
import sht31
import pycom
import math
import binascii


wlan = network.WLAN(mode=network.WLAN.STA)
wlan.connect('WiFi_Name', auth=(network.WLAN.WPA2, 'WiFi_Password'))

while not wlan.isconnected():
    machine.idle()

print("Connected to Wifi\n")
client = MQTTClient("pi", "IP", port=1883)

client.connect()
time.sleep(10)
uart = UART(1, 9600, pins=("G28","G22"), timeout_chars=2000)
i2c = I2C(0, I2C.MASTER, baudrate=100000)
sensor = sht31.SHT31(i2c, addr=0x44)
rtc = machine.RTC()
rtc.ntp_sync("tw.pool.ntp.org", 3600)
sd = SD()
os.mount(sd, '/sd')

# check the content
os.listdir('/sd')

# try some standard file operations
コード例 #13
0
def mqtt():
    global c, subtopic, pubtopic, led_sw
    SERVER = "public.iot-as-mqtt.cn-shanghai.aliyuncs.com"
    USER = info['detail']['iotId']
    PWD = info['detail']['iotToken']
    CLIENT_ID = info['detail']['deviceName']
    c = MQTTClient(client_id=CLIENT_ID,
                   server=SERVER,
                   user=USER,
                   password=PWD,
                   keepalive=300)
    c.DEBUG = True
    c.set_callback(sub_cb)
    subtopic = "/" + info['detail']['productKey'] + "/" + info['detail'][
        'deviceName'] + "/r"
    pubtopic = b"/" + info['detail']['productKey'] + "/" + info['detail'][
        'deviceName'] + "/s"
    print("user:"******"CLIENT_ID:", CLIENT_ID, subtopic, "/r", pubtopic)
    if not c.connect(clean_session=False):
        print("Ne session being set .")
        c.subscribe(subtopic)
    c.publish(pubtopic, "System Started!")

    for a in range(1, 5):
        sleep(1)
        lib.bb(5)
    timer = 0
    #LED初始化
    led_time.initialize(1)
    led_flag = 0
    while 1:
        time.sleep(1)
        if led_sw == 1:
            # print ("led",led_flag)
            pin(led[led_flag], 0)
            led_flag += 1
            if led_flag == 4:
                led_flag = 0
            pin(led[led_flag], 1)
        else:
            for aa in led:
                pin(aa, 0)
        #喂狗
        WDT().feed()
        c.check_msg()
        resp = uart.read()
        if resp != None:
            c.publish(pubtopic, playload(str(resp)))
        #循环时间变量
        _time = RTC().datetime()
        #oled屏幕时间
        led_time.showDots(1) if timer % 2 == 1 else led_time.showDots(0)
        led_time.disp_number(
            int(
                str(_time[4]) +
                (str(_time[5]) if _time[5] > 9 else '0' + str(_time[5]))))
        c.check_msg()

        timer += 1
        if timer % 5 == 0:
            wd()
            led_time.showDots(0)
            time.sleep(0.3)
        if ds == 1:
            #每天更新网络时间
            if _time[4] == 2 and _time[5] == 1 and _time[6] == 1:
                #到点重启
                machine.reset()
            #整点
            if _time[5] == 1 and _time[6] == 1:
                lib.bb(5)
                time.sleep(1)
                lib.bb(5)
                time.sleep(1)
                lib.bb(5)
                lib.update_time()
            #半点
            if _time[5] == 30 and _time[6] == 1:
                lib.bb(14, f=500)
                time.sleep(1)
                lib.bb(14, f=500)
                time.sleep(1)
                lib.bb(14, f=500)
            if _time[4] == 7 and _time[5] == 50 and _time[6] == 1:
                uart.write("AT+FRE=1046")
                pin(16, 0)
            if _time[4] < 6:

                led_sw = 0

        #TH=dht11(17)

        #print("温度:%s,湿度%s"%(TH[0],TH[1]))

        #断网重启

        if not network.WLAN(network.STA_IF).isconnected():

            print('断网重启...')

            lib.bb(5)
            lib.bb(5)
            lib.bb(5)
            lib.bb(5)
            lib.bb(5)
            machine.reset()
コード例 #14
0
        'data': msg,
        'deviceType': deviceType
    })
    print("Mqtt发送>>>>", _data)
    return _data


#mqtt 连接部分

SERVER = "public.iot-as-mqtt.cn-shanghai.aliyuncs.com"
USER = info['detail']['iotId']
PWD = info['detail']['iotToken']
CLIENT_ID = info['detail']['deviceName']
c = MQTTClient(client_id=CLIENT_ID,
               server=SERVER,
               user=USER,
               password=PWD,
               keepalive=300)
c.DEBUG = True
c.set_callback(sub_cb)
subtopic = "/" + info['detail']['productKey'] + "/" + info['detail'][
    'deviceName'] + "/r"
pubtopic = b"/" + info['detail']['productKey'] + "/" + info['detail'][
    'deviceName'] + "/s"
print(subtopic, "/r", pubtopic)
if not c.connect(clean_session=False):
    print("Ne session being set .")
    c.subscribe(subtopic)
#发送连接状态
c.publish(pubtopic, playload('{"state":"connected"}'))
while 1:
コード例 #15
0
import time
import machine
import os
import sht31
import pycom
import math
import binascii

wlan = network.WLAN(mode=network.WLAN.STA)
wlan.connect('WiFi_Name', auth=(network.WLAN.WPA2, 'WiFi_Password'))

while not wlan.isconnected():
    machine.idle()

print("Connected to Wifi\n")
client = MQTTClient("pi", "IP", port=1883)

client.connect()
time.sleep(10)
uart = UART(1, 9600, pins=("G28", "G22"), timeout_chars=2000)
i2c = I2C(0, I2C.MASTER, baudrate=100000)
sensor = sht31.SHT31(i2c, addr=0x44)
rtc = machine.RTC()
rtc.ntp_sync("tw.pool.ntp.org", 3600)
sd = SD()
os.mount(sd, '/sd')

# check the content
os.listdir('/sd')

# try some standard file operations
コード例 #16
0
import network
from robust import MQTTClient
from settings import MQTT_HOSTNAME, MQTT_PORT, MQTT_USER, MQTT_PASSWORD
import status

def sub_cb(topic, msg):
    print((topic, msg))
    if msg == b'beacon':
        status.beacon()

c = MQTTClient('umqtt_client',
               MQTT_HOSTNAME,
               port = MQTT_PORT,
               user = MQTT_USER,
               password = MQTT_PASSWORD)

try:
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b'events')
    c.publish(b'status', b'hi')
except:
    status.error()
    print('MQTT hello failed')

try:
    sta_if = network.WLAN(network.STA_IF)
    c.publish(b'status', b'ip: %s' % (sta_if.ifconfig()[0],))
except:
    print('MQTT IP publish failed')