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):
    switch_demo(msg.decode('utf-8')) #doesn't recognise decode

    def PON():
    return "ON"

    def POFF():
    return "OFF"

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

  • 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 = a.decode("utf-8")
    >>> print(b)

    please look at formating rules of the forum here

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

Log in to reply

Pycom on Twitter