mqtt message directed to switc-case issue



  • It appears that the message from a mqtt subscription are bytes as when i print them, i get b'PON' for example. I have a switcher statement to execute a function based on the message but it appears to have issues with it being in bytes and i cannot decode it.

    def sub_cb(topic, msg):
    print("mqtt::",topic,"msg[",msg,"]")
    switch_demo(msg.decode('utf-8')) #doesn't recognise decode

    def PON():
    p_out.value(True)
    return "ON"

    def POFF():
    p_out.value(False)
    return "OFF"

    def switch_demo(argument):
    print("switch_demo::argument[",argument,"]")
    switcher = {
    'PON': PON,
    'POFF': POFF,
    }
    # Get the function from switcher dictionary
    func = switcher.get(argument, lambda: "Invalid month")
    # Execute the function
    print(func())



  • its working now, not sure why, maybe the file were out of sync



  • @misterlisty
    are you sure that your problem is decode? - what is the error message?
    For me decode work without problem

    >>> a = b'PON'
    >>> print(a)
    b'PON'
    >>> b = a.decode("utf-8")
    >>> print(b)
    PON
    >>>
    

    please look at formating rules of the forum here
    http://commonmark.org/help/

    e.g. surround your code with triple ``` to make python code format


Log in to reply
 

Pycom on Twitter