You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

184 lines
6.7 KiB

  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Hardware Customer Display module for Odoo
  5. # Copyright (C) 2014 Akretion (http://www.akretion.com)
  6. # @author Alexis de Lattre <alexis.delattre@akretion.com>
  7. #
  8. # This program is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU Affero General Public License as
  10. # published by the Free Software Foundation, either version 3 of the
  11. # License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Affero General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Affero General Public License
  19. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. #
  21. ##############################################################################
  22. import logging
  23. import simplejson
  24. import time
  25. from threading import Thread, Lock
  26. from Queue import Queue
  27. import openerp.addons.hw_proxy.controllers.main as hw_proxy
  28. from openerp import http
  29. from openerp.tools.config import config
  30. logger = logging.getLogger(__name__)
  31. try:
  32. from serial import Serial
  33. from unidecode import unidecode
  34. except (ImportError, IOError) as err:
  35. logger.debug(err)
  36. class CustomerDisplayDriver(Thread):
  37. def __init__(self):
  38. Thread.__init__(self)
  39. self.queue = Queue()
  40. self.lock = Lock()
  41. self.status = {'status': 'connecting', 'messages': []}
  42. self.device_name = config.get(
  43. 'customer_display_device_name', '/dev/ttyUSB0')
  44. self.device_rate = int(config.get(
  45. 'customer_display_device_rate', 9600))
  46. self.device_timeout = int(config.get(
  47. 'customer_display_device_timeout', 2))
  48. self.serial = False
  49. def get_status(self):
  50. self.push_task('status')
  51. return self.status
  52. def set_status(self, status, message=None):
  53. if status == self.status['status']:
  54. if message is not None and message != self.status['messages'][-1]:
  55. self.status['messages'].append(message)
  56. else:
  57. self.status['status'] = status
  58. if message:
  59. self.status['messages'] = [message]
  60. else:
  61. self.status['messages'] = []
  62. if status == 'error' and message:
  63. logger.error('Display Error: '+message)
  64. elif status == 'disconnected' and message:
  65. logger.warning('Disconnected Display: '+message)
  66. def lockedstart(self):
  67. with self.lock:
  68. if not self.isAlive():
  69. self.daemon = True
  70. self.start()
  71. def push_task(self, task, data=None):
  72. self.lockedstart()
  73. self.queue.put((time.time(), task, data))
  74. def move_cursor(self, col, row):
  75. # Bixolon spec : 11. "Move Cursor to Specified Position"
  76. self.cmd_serial_write('\x1B\x6C' + chr(col) + chr(row))
  77. def display_text(self, lines):
  78. logger.debug(
  79. "Preparing to send the following lines to LCD: %s" % lines)
  80. # We don't check the number of rows/cols here, because it has already
  81. # been checked in the POS client in the JS code
  82. lines_ascii = []
  83. for line in lines:
  84. lines_ascii.append(unidecode(line))
  85. row = 0
  86. for dline in lines_ascii:
  87. row += 1
  88. self.move_cursor(1, row)
  89. self.serial_write(dline)
  90. def setup_customer_display(self):
  91. '''Set LCD cursor to off
  92. If your LCD has different setup instruction(s), you should
  93. inherit this function'''
  94. # Bixolon spec : 35. "Set Cursor On/Off"
  95. self.cmd_serial_write('\x1F\x43\x00')
  96. logger.debug('LCD cursor set to off')
  97. def clear_customer_display(self):
  98. '''If your LCD has different clearing instruction, you should inherit
  99. this function'''
  100. # Bixolon spec : 12. "Clear Display Screen and Clear String Mode"
  101. self.cmd_serial_write('\x0C')
  102. logger.debug('Customer display cleared')
  103. def cmd_serial_write(self, command):
  104. '''If your LCD requires a prefix and/or suffix on all commands,
  105. you should inherit this function'''
  106. assert isinstance(command, str), 'command must be a string'
  107. self.serial_write(command)
  108. def serial_write(self, text):
  109. assert isinstance(text, str), 'text must be a string'
  110. self.serial.write(text)
  111. def send_text_customer_display(self, text_to_display):
  112. '''This function sends the data to the serial/usb port.
  113. We open and close the serial connection on every message display.
  114. Why ?
  115. 1. Because it is not a problem for the customer display
  116. 2. Because it is not a problem for performance, according to my tests
  117. 3. Because it allows recovery on errors : you can unplug/replug the
  118. customer display and it will work again on the next message without
  119. problem
  120. '''
  121. lines = simplejson.loads(text_to_display)
  122. assert isinstance(lines, list), 'lines_list should be a list'
  123. try:
  124. logger.debug(
  125. 'Opening serial port %s for customer display with baudrate %d'
  126. % (self.device_name, self.device_rate))
  127. self.serial = Serial(
  128. self.device_name, self.device_rate,
  129. timeout=self.device_timeout)
  130. logger.debug('serial.is_open = %s' % self.serial.isOpen())
  131. self.setup_customer_display()
  132. self.clear_customer_display()
  133. self.display_text(lines)
  134. except Exception, e:
  135. logger.error('Exception in serial connection: %s' % str(e))
  136. finally:
  137. if self.serial:
  138. logger.debug('Closing serial port for customer display')
  139. self.serial.close()
  140. def run(self):
  141. while True:
  142. try:
  143. timestamp, task, data = self.queue.get(True)
  144. if task == 'display':
  145. self.send_text_customer_display(data)
  146. elif task == 'status':
  147. pass
  148. except Exception as e:
  149. self.set_status('error', str(e))
  150. driver = CustomerDisplayDriver()
  151. hw_proxy.drivers['customer_display'] = driver
  152. class CustomerDisplayProxy(hw_proxy.Proxy):
  153. @http.route(
  154. '/hw_proxy/send_text_customer_display', type='json', auth='none',
  155. cors='*')
  156. def send_text_customer_display(self, text_to_display):
  157. logger.debug(
  158. 'LCD: Call send_text_customer_display with text=%s',
  159. text_to_display)
  160. driver.push_task('display', text_to_display)