我想实现一种“第一次看到”和“最后见过”的方式来跟踪来自RFID阅读器的消息。
以下代码设法跟踪每条唯一邮件并每隔5分钟更新一次。
import paho.mqtt.client as mqtt
import json
import datetime as dt
time_interval = dt.timedelta(minutes=5)
dic1 = {}
update = []
def on_message(client, userdata, msg):
payloadjson = json.loads(msg.payload.decode('utf-8'))
line = payloadjson["value"].split(',')
epc = line[1]
rfid_input = "EPC_NO.: " + epc[11:35]
when = dt.datetime.strptime(datetime, '%Y-%m-%d %H:%M:%S')
if rfid_input not in dic1 or (when - dic1[rfid_input] > time_interval):
dic1[rfid_input] = when
update.append(dic1)
for key, value in update[-1].items():
print (key, value)
print ()
如何跟踪“第一次见到”的日期和时间时间并打印出来?
类似的东西:
# At the very beginning
EPC_NO.: 012345 FIRST SEEN AT 2016-04-18 08:59:33 LAST SEEN AT 2016-04-18 08:59:33
EPC_NO.: 056789 FIRST SEEN AT 2016-04-18 09:00:23 LAST SEEN AT 2016-04-18 09:00:23
# 5 mins later
EPC_NO.: 012345 FIRST SEEN AT 2016-04-18 08:59:33 LAST SEEN AT 2016-04-18 09:04:33
EPC_NO.: 056789 FIRST SEEN AT 2016-04-18 09:00:23 LAST SEEN AT 2016-04-18 09:05:23
# 10 mins later **(EPC_NO.: 056789 is not read)
EPC_NO.: 012345 FIRST SEEN AT 2016-04-18 08:59:33 LAST SEEN AT 2016-04-18 09:09:33
EPC_NO.: 056789 FIRST SEEN AT 2016-04-18 09:00:23 LAST SEEN AT 2016-04-18 09:05:23
答案 0 :(得分:1)
我会使用课程来收集您需要的所有信息:
import paho.mqtt.client as mqtt
import json
import datetime as dt
time_interval = dt.timedelta(minutes=5)
dic1 = {}
class EPC():
def __init__(self,when):
self.first_seen = when
self.last_print = when
self.last_seen = when
def on_message(client, userdata, msg):
payloadjson = json.loads(msg.payload.decode('utf-8'))
line = payloadjson["value"].split(',')
epc = line[1]
rfid_input = "EPC_NO.: " + epc[11:35]
when = dt.datetime.today()
if rfid_input not in dic1:
dic1[rfid_input] = EPC(when)
print_all = True
else:
dic1[rfid_input].last_seen = when
print_all = when-dic1[rfid_input].last_print > time_interval
if print_all:
for (key, value) in dic1.items():
first_str = "%04d-%02d-%02d %02d:%02d:%02d"%(value.first_seen.year,value.first_seen.month,value.first_seen.day,value.first_seen.hour,value.first_seen.minute,value.first_seen.second)
last_str = "%04d-%02d-%02d %02d:%02d:%02d"%(value.last_seen.year,value.last_seen.month,value.last_seen.day,value.last_seen.hour,value.last_seen.minute,value.last_seen.second)
print "EPC_NO.: %06d FIRST SEEN AT %s LAST SEEN AT %s"%(key, first_str,last_str)
value.last_print = when
我无法测试,所以告诉我是否有问题。