mqtt on/off message on button press



  • for those who searched and need a simple sketch on how to send an ON/OFF MQTT message with a switch here it is:

    Based on a GPY, commented are for WIFI, use accordingly.

    enjoy.

    from network import LTE
    from machine import Pin
    from umqtt import MQTTClient
    import machine
    import time
    
    
    is_pressed = False
    button = Pin("P10", mode=Pin.IN, pull=Pin.PULL_UP)
    
    
    
    
    def settimeout(duration):
         pass
    lte = LTE()
    
     # Modem does not connect successfully without first being reset.
    print("Resetting LTE modem ... ", end='')
    lte.send_at_cmd('AT^RESET')
    print("OK")
    time.sleep(1)
    
    print("Configuring LTE ", end='')
    lte.send_at_cmd('AT+CGDCONT=1,"IP","yourAPN"')
    print(".", end='')
    lte.send_at_cmd('AT!="RRC::addscanfreq band=2, 4, 5 dl-earfcn=9410"')
    print(".", end='')
    lte.send_at_cmd('AT+CFUN=1')
    print(" OK")
    
    if not lte.isattached():
        print("Attaching to LTE network ", end='')
        lte.attach()
        while(True):
            if lte.isattached():
                print(" OK")
                break
            print('.', end='')
            time.sleep(1)
    
        # Once attached, connect() should succeed.
        if not lte.isconnected():
            print("Connecting on LTE network ", end='')
            lte.connect()
            while(True):
                if lte.isconnected():
                    print(" OK")
                    break
                print('.', end='')
                time.sleep(1)
    lte.connect()
    while not lte.isconnected():
        machine.idle()
    
    print("Connected to LTE\n")
    #wlan = WLAN(mode=WLAN.STA)
    #wlan.antenna(WLAN.EXT_ANT)
    #wlan.connect("yourwifi", auth=(WLAN.WPA2, "yourpass"), timeout=5000)
    
    #while not wlan.isconnected():
    
    
    #print("Connected to Wifi\n")
    client = MQTTClient("joe", "yourMQTTbroker", port=1883)
    client.settimeout = settimeout
    client.connect()
    
    while True:
        if button() == 1 and not is_pressed:
            time.sleep(1)
        elif button() == 0 and not is_pressed:
            print("Button pressed")
            print("Sending ON")
            client.publish("/gpy", "ON")
            is_pressed = True
            time.sleep(1)
        elif button() == 1 and is_pressed:
            print("Button released")
            print("Sending OFF")
            client.publish("/gpy", "OFF")
            is_pressed = False
            time.sleep(1)
        else:
            pass
    

Log in to reply
 

Pycom on Twitter