1 | import sys, os |
---|
2 | import serial |
---|
3 | import array |
---|
4 | import time |
---|
5 | import optparse |
---|
6 | import ConfigParser |
---|
7 | import logging |
---|
8 | |
---|
9 | logging.basicConfig(level=logging.INFO) |
---|
10 | log = logging.getLogger( 'ScannerInterface' ) |
---|
11 | |
---|
12 | class ScannerInterface( object ): |
---|
13 | cmdprefix = [22, 77, 13] |
---|
14 | response = { 6: 'ACK', 5: 'ENQ', 21: 'NAK' } |
---|
15 | |
---|
16 | def __init__( self, port ): |
---|
17 | if os.name in ['posix', 'mac']: |
---|
18 | self.port = port |
---|
19 | elif os.name == 'nt': |
---|
20 | self.port = int(port) |
---|
21 | if self.port: |
---|
22 | self.open() |
---|
23 | |
---|
24 | def open(self): |
---|
25 | try: |
---|
26 | self.serial_conn = serial.Serial(self.port) |
---|
27 | except serial.SerialException: |
---|
28 | log.exception('Unable to open port: %s' % str(self.port)) |
---|
29 | sys.exit(1) |
---|
30 | log.debug('Port %s is open: %s' %( str(self.port), self.serial_conn.isOpen() ) ) |
---|
31 | |
---|
32 | def is_open(self): |
---|
33 | return self.serial_conn.isOpen() |
---|
34 | |
---|
35 | def close(self): |
---|
36 | self.serial_conn.close() |
---|
37 | log.debug('Port %s is open: %s' %( str(self.port), self.serial_conn.isOpen() ) ) |
---|
38 | |
---|
39 | def send(self, msg): |
---|
40 | message = self.cmdprefix + map(ord, msg) |
---|
41 | byte_array = array.array('B', message) |
---|
42 | log.debug('Sending message to %s: %s' % ( str(self.port), message) ) |
---|
43 | bytes = self.serial_conn.write( byte_array.tostring() ) |
---|
44 | log.debug('%i bytes out of %i bytes sent to the scanner' % ( bytes, len(message) ) ) |
---|
45 | |
---|
46 | def recv(self): |
---|
47 | time.sleep(1) |
---|
48 | self.serial_conn.flush() |
---|
49 | nbytes = self.serial_conn.inWaiting() |
---|
50 | log.debug('%i bytes received' % nbytes) |
---|
51 | if nbytes: |
---|
52 | msg = self.serial_conn.read(nbytes) |
---|
53 | byte_array = map(ord, msg) |
---|
54 | log.debug('Message received [%s]: %s' % (self.response.get(byte_array[len(byte_array)-2], byte_array[len(byte_array)-2]), |
---|
55 | msg)) |
---|
56 | return msg |
---|
57 | else: |
---|
58 | log.error('Error!') |
---|
59 | return None |
---|
60 | |
---|
61 | def setup_recv(self, callback): |
---|
62 | self.recv_callback = callback |
---|
63 | |
---|
64 | def wait(self): |
---|
65 | nbytes = self.serial_conn.inWaiting() |
---|
66 | if nbytes: |
---|
67 | msg = self.serial_conn.read(nbytes) |
---|
68 | byte_array = map(ord, msg) |
---|
69 | log.debug('Message received [%s]: %s' % (self.response.get(byte_array[len(byte_array)-2], byte_array[len(byte_array)-2], |
---|
70 | msg))) |
---|
71 | if self.recv_callback: |
---|
72 | self.recv_callback(msg) |
---|
73 | return |
---|
74 | |
---|
75 | |
---|
76 | |
---|