2016-04-06 10 views
0

私は自分のメッセージをRFIDリーダーで受信しています。自分のID(この場合はepc)は リストを選択的に追加するには?

  • datetime(行われる)ユニークで、ある場合

    1. :私は何をしようとしていることは重複を削除し、2つのだけ条件以下のリストに追加することです5分間隔の後にされた(まだRFIDリーダで読み取っているので、私は同じタグを追跡することができ、すべて5分)

      import paho.mqtt.client as mqtt 
      import json 
      
      testlist = []  
      
      def on_message(client, userdata, msg): 
          payloadjson = json.loads(msg.payload.decode('utf-8')) 
          line = payloadjson["value"].split(',') 
          epc = line[1] 
          datetime = payloadjson['datetime'] 
          # datetime is in this string format '2016-04-06 03:21:17' 
      
          payload = {'datetime': datetime, 'epc': epc[11:35]} 
      
          # this if-statement satisfy condition 1 
          if payload not in testlist: 
           testlist.append(payload) 
           for each in teslist: 
            print (each) 
      
      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() 
      

    どのように私ができます条件2を達成する?

    私は

    私の所望の出力は次のようなものになります達成しようとしている不明確な目標のために謝罪UPDATE
    :これはおそらく容易にすることができ

    {'datetime': 2016-04-06 03:21:17', 'epc': 00000001} # from Tag A 
    {'datetime': 2016-04-06 03:21:18', 'epc': 00000002} # from Tag B 
    ... 
    ... 
    # 5 minutes later 
    {'datetime': 2016-04-06 03:21:17', 'epc': 00000001} # from Tag A 
    {'datetime': 2016-04-06 03:21:18', 'epc': 00000002} # from Tag B 
    {'datetime': 2016-04-06 03:26:17', 'epc': 00000001} # from Tag A 
    {'datetime': 2016-04-06 03:26:18', 'epc': 00000002} # from Tag B 
    ... 
    ... 
    # Another 5 minutes later 
    {'datetime': 2016-04-06 03:21:17', 'epc': 00000001} # from Tag A 
    {'datetime': 2016-04-06 03:21:18', 'epc': 00000002} # from Tag B 
    {'datetime': 2016-04-06 03:26:17', 'epc': 00000001} # from Tag A 
    {'datetime': 2016-04-06 03:26:18', 'epc': 00000002} # from Tag B 
    {'datetime': 2016-04-06 03:31:17', 'epc': 00000001} # from Tag A 
    {'datetime': 2016-04-06 03:31:18', 'epc': 00000002} # from Tag B 
    ... 
    ... 
    
  • 答えて

    1

    あなたの質問は少し不明です。新しいepcの場合、またはepcへの最後の更新から5分を超えている場合は、testlistを更新したいと仮定します。この場合、dict()がうまくいくでしょう。標準ライブラリのdatetimeモジュールを使用して、日付または時刻の違いを計算します。

    import paho.mqtt.client as mqtt 
    import json 
    import datetime as dt 
    
    TIMELIMIT = dt.timedelta(minutes=5) 
    
    testlist = {}  ## <<-- changed this to a dict() 
    
    def on_message(client, userdata, msg): 
        payloadjson = json.loads(msg.payload.decode('utf-8')) 
        line = payloadjson["value"].split(',') 
        epc = line[1] 
    
        # this converts the time stamp string to something python can 
        # use in date/time calculations 
        when = dt.datetime.strptime(payloadjson['datetime'], '%Y-%m-%d %H:%M:%S') 
    
        if epc not in testlist or when - testlist[epc] > TIMELIMIT: 
         testlist[epc] = when 
    
         for epc, when in teslist.items(): 
          print (epc, when) 
    
    +0

    回答ありがとうございます! 'testlist ['epc']' vs 'testlist [epc]'の違いは何ですか?私の現在の理解では、前者は単純に 'testc'のキーとして' epc'を使うことを意味します。後者はどうでしょうか?何が「魔法」ですか? –

    +1

    '' epc''は 'e'、' p'、 'c'の3文字からなる文字列リテラルです。 'testlist ['epc']'はそのリテラル文字列をキーとして使用しています。対照的に、 'epc'は変数名であり、任意の値にバインドすることができます。例えば、 'epc = 42'は名前' epc'を値 '42'に束縛します。 'testlist [epc]'は 'epc'という名前にバインドされた値をキーとして使います。 – RootTwo

    2

    をアプローチ:

    class EPC(object): 
        def __init__(self, epc, date): 
         self.epc = epc 
         self.datetime = date 
        def __eq__(self, other): 
         difference = datetime.strptime(self.datetime, '%Y-%m-%d %H:%M:%S') - datetime.strptime(other.datetime, '%Y-%m-%d %H:%M:%S') 
         return self.epc == other.epc and timedelta(minutes=-5) < difference < timedelta(minutes=5) 
        def __ne__(self, other): 
         difference = datetime.strptime(self.datetime, '%Y-%m-%d %H:%M:%S') - datetime.strptime(other.datetime, '%Y-%m-%d %H:%M:%S') 
         return self.epc != other.epc or (self.epc == other.epc and (difference > timedelta(minutes=5) or difference < timedelta(minutes=-5))) 
    
    payload = EPC(date, epc[11:35]) 
    if payload not in test_list: 
        test_list.append(payload) 
    
    1

    epcの値を前後に入れ替えることができるのだろうかと思う。つまり、epc値 'A'が表示され、epc値 'B'が表示され、epc値 'A'が再び表示される可能性がありますか? (あるいはA、B、C、など?)

    仮定が唯一のそしてちょうど最新のエントリを見て、1個のタグがあるだろうということであれば:

    last_tag = testlist[-1] 
    last_dt = last_tag['datetime'] 
    

    今、あなたは比較することができます現在の値がdatetimeで、ウィンドウに収まるかどうかを確認してください。

    datetimeが変更されているので、実際には既存のコードでdatetimeコードを使用することはできませんので、正確に同じ2つのRFID読み取りを行わない限り、payload not in testlistは常にtrueになります秒。

    0

    あなたの問題に対処するためにいくつかのポイントがあります:IDの一意性については

    1. が​​オブジェクトがdatetimeを含んでいるので、あなたは、全体​​オブジェクトのみepcフィールドをチェックする必要はありません。表示されたすべてのIDを保存するにはsetを使用できます。時間をチェックするための
    2. 、時間に
    # -*- coding: utf-8 -*- 
    """ 
    06 Apr 2016 
    To answer http://stackoverflow.com/questions/36440618/ 
    """ 
    
    # Import statements 
    
    # import paho.mqtt.client as mqtt 
    import json 
    import datetime as dt 
    
    testlist = [] 
    seen_ids = set() # The set of seen IDs 
    five_minutes = dt.timedelta(minutes=5) # The five minutes differences 
    
    def on_message(client, userdata, msg): 
        payloadjson = json.loads(msg.payload.decode('utf-8')) 
        line = payloadjson["value"].split(',') 
        epc = line[1] 
        datetime = payloadjson['datetime'] 
        # datetime is in this string format '2016-04-06 03:21:17' 
    
        # Convert the string into datetime object 
        datetime = dt.datetime.strptime(datetime, '%Y-%m-%d %H:%M:%S') 
    
        payload = {'datetime': datetime, 'epc': epc[11:35]} 
    
        # this if-statement satisfy condition 1 
        if payload['epc'] not in seen_ids: # Need to use another set 
         should_add = True    # The flag whether to add 
         if len(testlist) > 0: 
          last_payload = testlist[-1] 
          diff = payload['datetime'] - last_payload['datetime'] 
          if diff < five_minutes:  # If the newer one is less than five minutes, do not add 
           should_add = False 
         if should_add: 
          seen_ids.add(payload['epc']) # Mark as seen 
          testlist.append(payload) 
          print ('Content of testlist now:') 
          for each in testlist: 
           print (each) 
    
    class Message(object): 
        def __init__(self, payload): 
         self.payload = payload 
    
    def main(): 
        test_cases = [] 
        for i in range(10): 
         payload = '{{"value":",{}","datetime":"2016-04-06 03:{:02d}:17"}}'.format('0'*34+str(i), i) 
         test_case = Message(payload) 
         test_cases.append(test_case) 
        for test_case in test_cases: 
         on_message(None, None, test_case) 
    
    if __name__ == '__main__': 
        main() 
    

    を比較するdatetimetimedeltaオブジェクトを使用して印刷します:

     
    Content of testlist now: 
    {'epc': u'000000000000000000000000', 'datetime': datetime.datetime(2016, 4, 6, 3, 0, 17)} 
    Content of testlist now: 
    {'epc': u'000000000000000000000000', 'datetime': datetime.datetime(2016, 4, 6, 3, 0, 17)} 
    {'epc': u'000000000000000000000005', 'datetime': datetime.datetime(2016, 4, 6, 3, 5, 17)} 
    
    関連する問題