Permalink
Browse files

making this thing more infinite loop friendly

  • Loading branch information...
1 parent d1ec7ab commit 4b0ac61262cab1fc667435e8fe38dacf757de84c @tenderlove committed Jun 2, 2009
Showing with 31 additions and 16 deletions.
  1. +31 −12 lib/nfc.rb
  2. +0 −4 lib/nfc/lib_nfc.rb
View
43 lib/nfc.rb
@@ -1,37 +1,40 @@
require 'singleton'
+require 'thread'
require 'nfc/lib_nfc'
class NFC
VERSION = '1.0.0'
- attr_reader :device
-
include Singleton
def initialize
- @device = NFC::LibNFC::Device.new(NFC::LibNFC.nfc_connect)
- LibNFC.nfc_reader_init(@device.pointer)
+ @device = nil
+ @mutex = Mutex.new
end
def deactivate_field
- LibNFC.nfc_configure @device.pointer, LibNFC::DCO_ACTIVATE_FIELD, 0
+ LibNFC.nfc_configure device.pointer, LibNFC::DCO_ACTIVATE_FIELD, 0
end
def activate_field
- LibNFC.nfc_configure @device.pointer, LibNFC::DCO_ACTIVATE_FIELD, 1
+ LibNFC.nfc_configure device.pointer, LibNFC::DCO_ACTIVATE_FIELD, 1
end
def crc= value
- LibNFC.nfc_configure @device.pointer, LibNFC::DCO_HANDLE_CRC, value ? 1 : 0
+ LibNFC.nfc_configure device.pointer, LibNFC::DCO_HANDLE_CRC, value ? 1 : 0
end
def parity= v
- LibNFC.nfc_configure @device.pointer, LibNFC::DCO_HANDLE_PARITY, v ? 1 : 0
+ LibNFC.nfc_configure device.pointer, LibNFC::DCO_HANDLE_PARITY, v ? 1 : 0
+ end
+
+ def device
+ @device ||= connect
end
def infinite_list_passive= v
LibNFC.nfc_configure(
- @device.pointer,
+ device.pointer,
LibNFC::DCO_INFINITE_LIST_PASSIVE,
v ? 1 : 0
)
@@ -40,7 +43,7 @@ def infinite_list_passive= v
def poll_mifare
thing = LibNFC::ISO1443A.new
LibNFC.nfc_reader_list_passive(
- @device.pointer,
+ device.pointer,
LibNFC::IM_ISO14443A_106,
nil,
0,
@@ -50,11 +53,27 @@ def poll_mifare
end
def find
+ @mutex.lock
deactivate_field
- self.infinite_list_passive = false
+ self.infinite_list_passive = block_given?
self.crc = true
self.parity = true
activate_field
- poll_mifare
+ tag = poll_mifare
+ disconnect
+ @mutex.unlock
+ yield tag if block_given?
+ tag
+ end
+
+ private
+ def connect
+ device = NFC::LibNFC::Device.new(NFC::LibNFC.nfc_connect)
+ LibNFC.nfc_reader_init(device.pointer)
+ device
+ end
+
+ def disconnect
+ LibNFC.nfc_disconnect device.pointer
end
end
View
4 lib/nfc/lib_nfc.rb
@@ -24,10 +24,6 @@ class Device < FFI::Struct
def name
pointer.read_string
end
-
- def self.release ptr
- LibNFC.nfc_disconnect ptr
- end
end
class ISO1443A < FFI::Struct

0 comments on commit 4b0ac61

Please sign in to comment.