-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscanner.py
More file actions
68 lines (58 loc) · 2.19 KB
/
scanner.py
File metadata and controls
68 lines (58 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env python3
import serial
import RPi.GPIO as GPIO
class BarcodeScanner:
def __init__(self, trigger_pin=-1, port="/dev/ttyAMA0", baudrate=9600, timeout=1):
self.trigger_pin = trigger_pin
if trigger_pin != -1:
# Setup GPIO for scan trigger if configured
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.trigger_pin, GPIO.OUT)
GPIO.output(self.trigger_pin, 1)
self.__buffer = b""
self.conn = serial.Serial(port, baudrate, timeout=timeout)
"""Try to scan barcode, return None if none is found
"""
def scan(self, repeated_scan):
if self.trigger_pin != -1:
# Enable trigger pin
GPIO.output(self.trigger_pin, 0)
elif not repeated_scan:
# Scan will be active for set time, no need to resend on every interval
# Enable serial control
self.conn.write(b"\x7e\x00\x08\x01\x00\x00\xd5\xab\xcd")
# Extend time to 20s zone 0x0006 = C8h / 200d
self.conn.write(b"\x7e\x00\x08\x01\x00\x06\xc8\xab\xcd")
# Trigger scanning
self.conn.write(b"\x7e\x00\x08\x01\x00\x02\x01\xab\xcd")
while self.conn.in_waiting:
c = self.conn.read()
if c == b"\r" or c == b"\n":
if len(self.__buffer):
tmp = self.__buffer
self.__buffer = b""
return tmp.decode("utf-8")
else:
self.__buffer += c
if self.__buffer == b"\x02\x00\x00\x01\x00\x33\x31":
self.__buffer = b"" # remove handshake notice
return None
"""Release trigger
"""
def endScan(self):
if self.trigger_pin != -1:
# Disable trigger pin
GPIO.output(self.trigger_pin, 1)
else:
# Switch to manual trigger
self.conn.write(b"\x7e\x00\x08\x01\x00\x00\xd4\xab\xcd")
self.__buffer = b""
if __name__ == "__main__":
scanner = BarcodeScanner(18, "/dev/ttyS0")
import time
timeout = time.time() + 5
res = None
while res is None and timeout > time.time():
res = scanner.scan()
scanner.endScan()
print(res)