如何将唯一的传入消息附加到列表中?

时间:2016-03-28 06:41:19

标签: python mqtt iot paho

我正在使用RFID阅读器接收消息。我试图通过将重复消息附加到emptylist = []来避免重复消息,如果它们存在于列表中,则不会进一步附加消息。以下是我的代码:

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe("/whatver/#")

def on_message(client, userdata, msg): # when PUBLISH msg is rcvd frm the server
    payloadjson = json.loads(msg.payload.decode('utf-8'))
    line = payloadjson["value"].split(',')
    epc =  line[1]


    payload = {'a': epc[11:35], 'b':payloadjson["devicename"], 'c':payloadjson["sensorname"]}

    emptylist = []
    emptylist.append(payload)

    if payload not in emptylist:
        emptylist.append(payload)

    print (emptylist)

test = mqtt.Client(protocol = mqtt.MQTTv31)
test.connect(host=_host, port=1883, keepalive=60, bind_address="")
test.on_connect = on_connect
test.on_message = on_message
test.loop_forever() 

但是我得到的输出如下所示,表明payload附加了emptylist,但存储在多个单独的列表中。如果RFID阅读器仍在读取相同的标签,它会继续打印相同的输出。我想删除重复的邮件,即使RFID阅读器读取相同的标签也只保留一条。

[{'b': 'READERBASIN.3', 'c': 'ANTENNA.2', 'a': '000000000000130000624462'}] # from Tag A
[{'b': 'READERBASIN.3', 'c': 'ANTENNA.2', 'a': 'abcxxx000000130000627000'}] # from Tag B
[{'b': 'READERBASIN.3', 'c': 'ANTENNA.2', 'a': '000000000000130000624462'}] # from Tag A
[{'b': 'READERBASIN.3', 'c': 'ANTENNA.2', 'a': '000000000000130000624462'}] # from Tag A
.
.
.

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

正如其他答案所提到的,设置是避免存储或打印重复项的好方法。您可以使用列表执行此操作(效率较低),但是,当前代码中的逻辑不正确。每次调用emptylist时,它都会创建一个空的on_message,然后将新payload添加到其中,因此以下if payload not in emptylist:没有多大意义

您需要在emptylist回调之外初始化on_message。例如,

emptylist = []

def on_message(client, userdata, msg): # when PUBLISH msg is rcvd frm the server
    payloadjson = json.loads(msg.payload.decode('utf-8'))
    line = payloadjson["value"].split(',')
    epc =  line[1]

    payload = {
        'a': epc[11:35], 
        'b':payloadjson["devicename"], 
        'c':payloadjson["sensorname"],
    }

    if payload not in emptylist:
        emptylist.append(payload)
        print (emptylist)

那只会附加&如果新有效负载不在emptylist中,则打印新的有效负载。

使用集合执行相同的操作:

emptylist = set()

def on_message(client, userdata, msg): # when PUBLISH msg is rcvd frm the server
    payloadjson = json.loads(msg.payload.decode('utf-8'))
    line = payloadjson["value"].split(',')
    epc =  line[1]

    payload = {
        'a': epc[11:35], 
        'b':payloadjson["devicename"], 
        'c':payloadjson["sensorname"],
    }

    if payload not in emptylist:
        emptylist.add(payload)
        print (emptylist)

FWIW,emptylist是一个有点令人困惑的变量名称。 :)

答案 1 :(得分:0)

你可以检查是否存在,同时附加如下:

if payload not in emptylist:
   emptylist.append(payload)

您可以在最终输出中选择set(emptylist)