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