Search code examples
pythondjangorfid

How to deal with unstable data received from RFID reader?


My application has to connect and receive data from RFID reader for every 2 seconds so it has developed on django framework. Here are related lines in views.py:

HOST = '192.168.0.1'
PORT = 50007
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.settimeout(2)
soc.connect((HOST, PORT))
soc.send('tag.db.scan_tags(100)\r\n')
datum = soc.recv(128)

if datum.find("ok") > -1:
    soc.send('tag.read_id()\r\n')
    data = soc.recv(8192)

The application would render received data to a template as {{ data }} if the RFID reader found any RFID tag in its field. The problem occurs when there is no tag in field or tags cannot be read, {{ data }} variable would show nothing on the page.

I want my application able to show the last data that can be read. If there is no new data come, just show the latest one. The data would be changed only if new data come. This will makes my application more stable.

Any suggestion, please? Thank you very much.


Solution

  • One of the easier things to do would be to use Django's cache framework, and store the data in local memory, or memcached, or the database, etc. You could cache any data recieved, and used the cached data if you don't recieve data, or it's erroneous or whatever:

    from django.core.cache import cache
    
    # set cached data
    cache.set('data', data)
    # get cached data
    cache.get('data')
    

    You could also store the data other ways, on a model for instance. You should probably move the RFID reading portion out of the view, and use celery (or something else) to run it as a task, save the results, and just use the latest saved data in your view