begin Kernel::require 'serialport' rescue Exception require 'serialport' end module RfidUsbGomSensor class Node < Gom::Remote::Entry Defaults = { :device => "/dev/ttyUSB0", :baudrate => 9600, } include OAttr oattr :device, :baudrate def initialize path, options = {} @path = path @options = Defaults.merge(gnode @path).merge(options) puts "options: #{@options.inspect}" @ip = connection.callback_server.host @sp = SerialPort.new device, baudrate end # reader commands STX = 0x02 ETX = 0x03 GetInfo = [STX, 0x01, 0x47, 0x46, ETX].pack "c*" GoContinuous = [STX, 0x01, 0x43, 0x04, 0x46, ETX].pack "c*" def preroll #info = [0x02, 0x01, 0x47, 0x46, 0x03] #info.each {|c| @sp.putc c.to_i} @sp.puts GetInfo 2.times {@sp.getc} print "Detected reader: " 37.times {putc(@sp.getc)} print "\n" 6.times {@sp.getc} #continuous = [0x02, 0x01, 0x43, 0x04, 0x46, 0x03] #continuous.each {|c| @sp.putc c.to_i} @sp.puts GoContinuous 6.times {@sp.getc} end class << self def checksum buf, expected cc = (buf.unpack "C*").inject(0) { |cc, c| cc ^ c } (cc != expected) and raise "checksum missmatch: #{cc} != #{expected}" cc end def decode blk #validate rec = (blk.unpack 'c2Qc*') checksum blk[1..10], rec[4] puts "-#{rec.inspect}-" rec end end def detect buf = "" loop do buf << (blk = @sp.read(13)) stx, adx, uid, err, bcc, etx = (Node.decode buf) buf = "" end rescue SignalException => e :stop # if (e.signm == "INT") end def _detect =begin Format: 0 STX 0x02 1 ADR 0x01 2 UID7 0xE0 3 UID6 4 UID5 5 UID4 6 UID3 7 UID2 8 UID1 9 UID0 10 ERR 0x00 11 BCC XOR[1..10] 12 ETX 0x03 =end while @sp.getc!=0x02 do end # STX while @sp.getc!=0x01 do end # ADR v = 0 0.upto(7) do |i| v += @sp.getc*2**((7-i)*8) # UID end while @sp.getc!=0x00 do end # ERR puts "Detected tag: #{v}" connection.write "#{@path}/tags/#{v}:sensor_ip", @ip puts "-#{@sp.getc}-" # BCC while @sp.getc!=0x03 do end # ETX rescue SignalException => e :stop # if (e.signm == "INT") end end end