938fa064d52062166c5488b0567bf75698374b4f
[odoo/odoo.git] / addons / hw_escpos / controllers / main.py
1 # -*- coding: utf-8 -*-
2 import commands
3 import logging
4 import simplejson
5 import os
6 import io
7 import base64
8 import openerp
9 import time
10 import random
11 import math
12 import md5
13 import openerp.addons.hw_proxy.controllers.main as hw_proxy
14 import subprocess
15 import traceback
16 from threading import Thread, Lock
17 from Queue import Queue, Empty
18
19 try:
20     import usb.core
21 except ImportError:
22     usb = None
23
24 try:
25     from .. import escpos
26     from ..escpos import printer
27     from ..escpos import supported_devices
28 except ImportError:
29     escpos = printer = None
30
31 from PIL import Image
32
33 from openerp import http
34 from openerp.http import request
35 from openerp.addons.web.controllers.main import manifest_list, module_boot, html_template
36 from openerp.tools.translate import _
37
38 _logger = logging.getLogger(__name__)
39
40
41 class EscposDriver(Thread):
42     def __init__(self):
43         Thread.__init__(self)
44         self.queue = Queue()
45         self.lock  = Lock()
46         self.status = {'status':'connecting', 'messages':[]}
47
48     def connected_usb_devices(self):
49         connected = []
50         
51         for device in supported_devices.device_list:
52             if usb.core.find(idVendor=device['vendor'], idProduct=device['product']) != None:
53                 connected.append(device)
54         return connected
55
56     def lockedstart(self):
57         with self.lock:
58             if not self.isAlive():
59                 self.daemon = True
60                 self.start()
61     
62     def get_escpos_printer(self):
63         try:
64             printers = self.connected_usb_devices()
65             if len(printers) > 0:
66                 self.set_status('connected','Connected to '+printers[0]['name'])
67                 return escpos.printer.Usb(printers[0]['vendor'], printers[0]['product'])
68             else:
69                 self.set_status('disconnected','Printer Not Found')
70                 return None
71         except Exception as e:
72             self.set_status('error',str(e))
73             return None
74
75     def get_status(self):
76         self.push_task('status')
77         return self.status
78
79
80
81     def open_cashbox(self,printer):
82         printer.cashdraw(2)
83         printer.cashdraw(5)
84
85     def set_status(self, status, message = None):
86         if status == self.status['status']:
87             if message != None and message != self.status['messages'][-1]:
88                 self.status['messages'].append(message)
89         else:
90             self.status['status'] = status
91             if message:
92                 self.status['messages'] = [message]
93             else:
94                 self.status['messages'] = []
95
96         if status == 'error' and message:
97             _logger.error('ESC/POS Error: '+message)
98         elif status == 'disconnected' and message:
99             _logger.warning('ESC/POS Device Disconnected: '+message)
100
101     def run(self):
102         if not escpos:
103             _logger.error('ESC/POS cannot initialize, please verify system dependencies.')
104             return
105         while True:
106             try:
107                 timestamp, task, data = self.queue.get(True)
108
109                 printer = self.get_escpos_printer()
110
111                 if printer == None:
112                     if task != 'status':
113                         self.queue.put((timestamp,task,data))
114                     time.sleep(5)
115                     continue
116                 elif task == 'receipt': 
117                     if timestamp >= time.time() - 1 * 60 * 60:
118                         self.print_receipt_body(printer,data)
119                         printer.cut()
120                 elif task == 'xml_receipt':
121                     if timestamp >= time.time() - 1 * 60 * 60:
122                         printer.receipt(data)
123                 elif task == 'cashbox':
124                     if timestamp >= time.time() - 12:
125                         self.open_cashbox(printer)
126                 elif task == 'printstatus':
127                     self.print_status(printer)
128                 elif task == 'status':
129                     pass
130
131             except Exception as e:
132                 self.set_status('error', str(e))
133                 errmsg = str(e) + '\n' + '-'*60+'\n' + traceback.format_exc() + '-'*60 + '\n'
134                 _logger.error(errmsg);
135
136     def push_task(self,task, data = None):
137         self.lockedstart()
138         self.queue.put((time.time(),task,data))
139
140     def print_status(self,eprint):
141         localips = ['0.0.0.0','127.0.0.1','127.0.1.1']
142         ips =  [ c.split(':')[1].split(' ')[0] for c in commands.getoutput("/sbin/ifconfig").split('\n') if 'inet addr' in c ]
143         ips =  [ ip for ip in ips if ip not in localips ] 
144         eprint.text('\n\n')
145         eprint.set(align='center',type='b',height=2,width=2)
146         eprint.text('PosBox Status\n')
147         eprint.text('\n')
148         eprint.set(align='center')
149
150         if len(ips) == 0:
151             eprint.text('ERROR: Could not connect to LAN\n\nPlease check that the PosBox is correc-\ntly connected with a network cable,\n that the LAN is setup with DHCP, and\nthat network addresses are available')
152         elif len(ips) == 1:
153             eprint.text('IP Address:\n'+ips[0]+'\n')
154         else:
155             eprint.text('IP Addresses:\n')
156             for ip in ips:
157                 eprint.text(ip+'\n')
158
159         if len(ips) >= 1:
160             eprint.text('\nHomepage:\nhttp://'+ips[0]+':8069\n')
161
162         eprint.text('\n\n')
163         eprint.cut()
164
165     def print_receipt_body(self,eprint,receipt):
166
167         def check(string):
168             return string != True and bool(string) and string.strip()
169         
170         def price(amount):
171             return ("{0:."+str(receipt['precision']['price'])+"f}").format(amount)
172         
173         def money(amount):
174             return ("{0:."+str(receipt['precision']['money'])+"f}").format(amount)
175
176         def quantity(amount):
177             if math.floor(amount) != amount:
178                 return ("{0:."+str(receipt['precision']['quantity'])+"f}").format(amount)
179             else:
180                 return str(amount)
181
182         def printline(left, right='', width=40, ratio=0.5, indent=0):
183             lwidth = int(width * ratio) 
184             rwidth = width - lwidth 
185             lwidth = lwidth - indent
186             
187             left = left[:lwidth]
188             if len(left) != lwidth:
189                 left = left + ' ' * (lwidth - len(left))
190
191             right = right[-rwidth:]
192             if len(right) != rwidth:
193                 right = ' ' * (rwidth - len(right)) + right
194
195             return ' ' * indent + left + right + '\n'
196         
197         def print_taxes():
198             taxes = receipt['tax_details']
199             for tax in taxes:
200                 eprint.text(printline(tax['tax']['name'],price(tax['amount']), width=40,ratio=0.6))
201
202         # Receipt Header
203         if receipt['company']['logo']:
204             eprint.set(align='center')
205             eprint.print_base64_image(receipt['company']['logo'])
206             eprint.text('\n')
207         else:
208             eprint.set(align='center',type='b',height=2,width=2)
209             eprint.text(receipt['company']['name'] + '\n')
210
211         eprint.set(align='center',type='b')
212         if check(receipt['shop']['name']):
213             eprint.text(receipt['shop']['name'] + '\n')
214         if check(receipt['company']['contact_address']):
215             eprint.text(receipt['company']['contact_address'] + '\n')
216         if check(receipt['company']['phone']):
217             eprint.text('Tel:' + receipt['company']['phone'] + '\n')
218         if check(receipt['company']['vat']):
219             eprint.text('VAT:' + receipt['company']['vat'] + '\n')
220         if check(receipt['company']['email']):
221             eprint.text(receipt['company']['email'] + '\n')
222         if check(receipt['company']['website']):
223             eprint.text(receipt['company']['website'] + '\n')
224         if check(receipt['header']):
225             eprint.text(receipt['header']+'\n')
226         if check(receipt['cashier']):
227             eprint.text('-'*32+'\n')
228             eprint.text('Served by '+receipt['cashier']+'\n')
229
230         # Orderlines
231         eprint.text('\n\n')
232         eprint.set(align='center')
233         for line in receipt['orderlines']:
234             pricestr = price(line['price_display'])
235             if line['discount'] == 0 and line['unit_name'] == 'Unit(s)' and line['quantity'] == 1:
236                 eprint.text(printline(line['product_name'],pricestr,ratio=0.6))
237             else:
238                 eprint.text(printline(line['product_name'],ratio=0.6))
239                 if line['discount'] != 0:
240                     eprint.text(printline('Discount: '+str(line['discount'])+'%', ratio=0.6, indent=2))
241                 if line['unit_name'] == 'Unit(s)':
242                     eprint.text( printline( quantity(line['quantity']) + ' x ' + price(line['price']), pricestr, ratio=0.6, indent=2))
243                 else:
244                     eprint.text( printline( quantity(line['quantity']) + line['unit_name'] + ' x ' + price(line['price']), pricestr, ratio=0.6, indent=2))
245
246         # Subtotal if the taxes are not included
247         taxincluded = True
248         if money(receipt['subtotal']) != money(receipt['total_with_tax']):
249             eprint.text(printline('','-------'));
250             eprint.text(printline(_('Subtotal'),money(receipt['subtotal']),width=40, ratio=0.6))
251             print_taxes()
252             #eprint.text(printline(_('Taxes'),money(receipt['total_tax']),width=40, ratio=0.6))
253             taxincluded = False
254
255
256         # Total
257         eprint.text(printline('','-------'));
258         eprint.set(align='center',height=2)
259         eprint.text(printline(_('         TOTAL'),money(receipt['total_with_tax']),width=40, ratio=0.6))
260         eprint.text('\n\n');
261         
262         # Paymentlines
263         eprint.set(align='center')
264         for line in receipt['paymentlines']:
265             eprint.text(printline(line['journal'], money(line['amount']), ratio=0.6))
266
267         eprint.text('\n');
268         eprint.set(align='center',height=2)
269         eprint.text(printline(_('        CHANGE'),money(receipt['change']),width=40, ratio=0.6))
270         eprint.set(align='center')
271         eprint.text('\n');
272
273         # Extra Payment info
274         if receipt['total_discount'] != 0:
275             eprint.text(printline(_('Discounts'),money(receipt['total_discount']),width=40, ratio=0.6))
276         if taxincluded:
277             print_taxes()
278             #eprint.text(printline(_('Taxes'),money(receipt['total_tax']),width=40, ratio=0.6))
279
280         # Footer
281         if check(receipt['footer']):
282             eprint.text('\n'+receipt['footer']+'\n\n')
283         eprint.text(receipt['name']+'\n')
284         eprint.text(      str(receipt['date']['date']).zfill(2)
285                     +'/'+ str(receipt['date']['month']+1).zfill(2)
286                     +'/'+ str(receipt['date']['year']).zfill(4)
287                     +' '+ str(receipt['date']['hour']).zfill(2)
288                     +':'+ str(receipt['date']['minute']).zfill(2) )
289
290
291 driver = EscposDriver()
292
293 driver.push_task('printstatus')
294
295 hw_proxy.drivers['escpos'] = driver
296
297 class EscposProxy(hw_proxy.Proxy):
298     
299     @http.route('/hw_proxy/open_cashbox', type='json', auth='none', cors='*')
300     def open_cashbox(self):
301         _logger.info('ESC/POS: OPEN CASHBOX') 
302         driver.push_task('cashbox')
303         
304     @http.route('/hw_proxy/print_receipt', type='json', auth='none', cors='*')
305     def print_receipt(self, receipt):
306         _logger.info('ESC/POS: PRINT RECEIPT') 
307         driver.push_task('receipt',receipt)
308
309     @http.route('/hw_proxy/print_xml_receipt', type='json', auth='none', cors='*')
310     def print_receipt(self, receipt):
311         _logger.info('ESC/POS: PRINT XML RECEIPT') 
312         driver.push_task('xml_receipt',receipt)
313