changeset 435:80e403e107b1

more error handling Ignore-this: f0fdd453ae131f867fdffc558603d09a
author drewp@bigasterisk.com
date Sat, 13 Apr 2019 15:23:46 -0700
parents 2409446ccfa2
children aff8ca01f8eb
files service/rfid_pn532_py/rfid.py service/rfid_pn532_py/tags.py
diffstat 2 files changed, 23 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- a/service/rfid_pn532_py/rfid.py	Tue Apr 09 09:05:42 2019 -0700
+++ b/service/rfid_pn532_py/rfid.py	Sat Apr 13 15:23:46 2019 -0700
@@ -10,12 +10,12 @@
 import cyclone.web
 from cyclone.httpclient import fetch
 import cyclone
-import logging, time, json, random, string
+import logging, time, json, random, string, traceback
 from logsetup import log, enableTwistedLog
 from greplin import scales
 from greplin.scales.cyclonehandler import StatsHandler
 from export_to_influxdb import InfluxExporter
-from tags import NfcDevice, FakeNfc
+from tags import NfcDevice, FakeNfc, NfcError, AuthFailedError
 
 ROOM = Namespace('http://projects.bigasterisk.com/room/')
 
@@ -127,9 +127,15 @@
                             tag.writeBlock(1, randomBody())
                             textLit = Literal(tag.readBlock(1).rstrip('\x00'))
                     finally:
+                        # This might not be appropriate to call after
+                        # readBlock fails. I am getting double
+                        # exceptions.
                         tag.disconnect()
                     self.startCardRead(cardIdUri, textLit)
-        except OSError as e:
+        except AuthFailedError as e:
+            log.error(e)
+        except (NfcError, OSError) as e:
+            traceback.print_exc()
             log.error(e)
             reactor.stop()
     def flushOldReads(self, now):
--- a/service/rfid_pn532_py/tags.py	Tue Apr 09 09:05:42 2019 -0700
+++ b/service/rfid_pn532_py/tags.py	Sat Apr 13 15:23:46 2019 -0700
@@ -55,6 +55,13 @@
 
 pubkey = b'\xff\xff\xff\xff\xff\xff'
 
+class NfcError(Exception):
+    def __init__(self, code, strerror):
+        Exception.__init__(self, "%s [%s]" % (strerror, code))
+        self.code = code
+
+class AuthFailedError(NfcError): pass
+
 class NfcTag(object):
     def __init__(self, tag): #FreefareTag
         self.tag = tag
@@ -63,7 +70,13 @@
         if ret == 0:
             return
 
-        raise IOError(cast(freefare.freefare_strerror(self.tag), c_char_p).value)
+        msg = cast(freefare.freefare_strerror(self.tag), c_char_p).value
+        if msg == b'Mifare Authentication Failed':
+            # return code is -1 (!). I was excpecting
+            # AUTHENTICATION_ERROR=0xAE or something.
+            raise AuthFailedError(ret, msg)        
+            
+        raise NfcError(ret, msg)
         
     def tagType(self) -> str:
         typeNum = freefare.freefare_get_tag_type(self.tag)