forked from danslimmon/oscar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscan.py
201 lines (156 loc) · 6.7 KB
/
scan.py
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
#!/usr/bin/env python
from datetime import datetime
import struct
import select
import socket
import random
import json
import urllib2
import hashlib
import hmac
import base64
import trello
from twilio.rest import TwilioRestClient
from lib import trellodb
from lib import conf
def parse_scanner_data(scanner_data):
upc_chars = []
for i in range(0, len(scanner_data), 16):
chunk = scanner_data[i:i+16]
# The chunks we care about will match
# __ __ __ __ __ __ __ __ 01 00 __ 00 00 00 00 00
if chunk[8:10] != '\x01\x00' or chunk[11:] != '\x00\x00\x00\x00\x00':
continue
digit_int = struct.unpack('>h', chunk[9:11])[0]
upc_chars.append(str((digit_int - 1) % 10))
return ''.join(upc_chars)
class UPCAPI:
BASEURL = 'https://www.digit-eyes.com/gtin/v2_0'
def __init__(self, app_key, auth_key):
self._app_key = app_key
self._auth_key = auth_key
def _signature(self, upc):
h = hmac.new(self._auth_key, upc, hashlib.sha1)
return base64.b64encode(h.digest())
def _url(self, upc):
return '{0}/?upcCode={1}&field_names=description&language=en&app_key={2}&signature={3}'.format(
self.BASEURL, upc, self._app_key, self._signature(upc))
def get_description(self, upc):
"""Returns the product description for the given UPC.
`upc`: A string containing the UPC."""
url = self._url(upc)
json_blob = urllib2.urlopen(url).read()
return json.loads(json_blob)['description']
def local_ip():
"""Returns the IP that the local host uses to talk to the Internet."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("trello.com", 80))
addr = s.getsockname()[0]
s.close()
return addr
def generate_opp_id():
return ''.join(random.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', 12))
def opp_url(opp):
return 'http://{0}/learn-barcode/{1}'.format(local_ip(), opp['opp_id'])
def create_barcode_opp(trello_db, barcode):
"""Creates a learning opportunity for the given barcode and writes it to Trello.
Returns the dict."""
opp = {
'type': 'barcode',
'opp_id': generate_opp_id(),
'barcode': barcode,
'created_dt': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
trello_db.insert('learning_opportunities', opp)
return opp
def publish_barcode_opp(opp):
client = TwilioRestClient(conf.get()['twilio_sid'], conf.get()['twilio_token'])
message = client.sms.messages.create(body='''Hi! Oscar here. You scanned a code I didn't recognize. Care to fill me in? {0}'''.format(opp_url(opp)),
to='+{0}'.format(conf.get()['twilio_dest']),
from_='+{0}'.format(conf.get()['twilio_src']))
def match_barcode_rule(trello_db, barcode):
"""Finds a barcode rule matching the given barcode.
Returns the rule if it exists, otherwise returns None."""
rules = trello_db.get_all('barcode_rules')
for r in rules:
if r['barcode'] == barcode:
return r
return None
def match_description_rule(trello_db, desc):
"""Finds a description rule matching the given product description.
Returns the rule if it exists, otherwise returns None."""
rules = trello_db.get_all('description_rules')
for r in rules:
if r['search_term'].lower() in desc.lower():
return r
return None
def add_grocery_item(trello_api, item):
"""Adds the given item to the grocery list (if it's not already present)."""
# Get the current grocery list
grocery_board_id = conf.get()['trello_grocery_board']
all_lists = trello_api.boards.get_list(grocery_board_id)
grocery_list = [x for x in all_lists if x['name'] == conf.get()['trello_grocery_list']][0]
cards = trello_api.lists.get_card(grocery_list['id'])
card_names = [card['name'] for card in cards]
# Add item if it's not there already
if item not in card_names:
print "Adding '{0}' to grocery list".format(item)
trello_api.lists.new_card(grocery_list['id'], item)
else:
print "Item '{0}' is already on the grocery list; not adding".format(item)
trello_api = trello.TrelloApi(conf.get()['trello_app_key'])
trello_api.set_token(conf.get()['trello_token'])
trello_db = trellodb.TrelloDB(trello_api, conf.get()['trello_db_board'])
f = open(conf.get()['scanner_device'], 'rb')
while True:
print 'Waiting for scanner data'
# Wait for binary data from the scanner and then read it
scan_complete = False
scanner_data = ''
while True:
rlist, _wlist, _elist = select.select([f], [], [], 0.1)
if rlist != []:
new_data = ''
while not new_data.endswith('\x01\x00\x1c\x00\x01\x00\x00\x00'):
new_data = rlist[0].read(16)
scanner_data += new_data
# There are 4 more keystrokes sent after the one we matched against,
# so we flush out that buffer before proceeding:
[rlist[0].read(16) for i in range(4)]
scan_complete = True
if scan_complete:
break
# Parse the binary data as a barcode
barcode = parse_scanner_data(scanner_data)
print "Scanned barcode '{0}'".format(barcode)
# Match against barcode rules
barcode_rule = match_barcode_rule(trello_db, barcode)
if barcode_rule is not None:
add_grocery_item(trello_api, barcode_rule['item'])
continue
# Get the item's description
u = UPCAPI(conf.get()['digiteyes_app_key'], conf.get()['digiteyes_auth_key'])
try:
desc = u.get_description(barcode)
print "Received description '{0}' for barcode {1}".format(desc, repr(barcode))
except urllib2.HTTPError, e:
if 'UPC/EAN code invalid' in e.msg:
print "Barcode {0} not recognized as a UPC; creating learning opportunity".format(repr(barcode))
opp = create_barcode_opp(trello_db, barcode)
print "Publishing learning opportunity via SMS"
publish_barcode_opp(opp)
continue
elif 'Not found' in e.msg:
print "Barcode {0} not found in UPC database; creating learning opportunity".format(repr(barcode))
opp = create_barcode_opp(trello_db, barcode)
print "Publishing learning opportunity via SMS"
publish_barcode_opp(opp)
continue
else:
raise
# Match against description rules
desc_rule = match_description_rule(trello_db, desc)
if desc_rule is not None:
add_grocery_item(trello_api, desc_rule['item'])
continue
print "Don't know what to add for product description '{0}'".format(desc)