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.

287 lines
11 KiB

9 years ago
  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Hardware Telium Payment Terminal 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. import curses.ascii
  26. from threading import Thread, Lock
  27. from Queue import Queue
  28. import openerp.addons.hw_proxy.controllers.main as hw_proxy
  29. from openerp import http
  30. from openerp.tools.config import config
  31. logger = logging.getLogger(__name__)
  32. try:
  33. import pycountry
  34. from serial import Serial
  35. except (ImportError, IOError) as err:
  36. logger.debug(err)
  37. class TeliumPaymentTerminalDriver(Thread):
  38. def __init__(self):
  39. Thread.__init__(self)
  40. self.queue = Queue()
  41. self.lock = Lock()
  42. self.status = {'status': 'connecting', 'messages': []}
  43. self.device_name = config.get(
  44. 'telium_terminal_device_name', '/dev/ttyACM0')
  45. self.device_rate = int(config.get(
  46. 'telium_terminal_device_rate', 9600))
  47. self.serial = False
  48. def get_status(self):
  49. self.push_task('status')
  50. return self.status
  51. def set_status(self, status, message=None):
  52. if status == self.status['status']:
  53. if message is not None and message != self.status['messages'][-1]:
  54. self.status['messages'].append(message)
  55. else:
  56. self.status['status'] = status
  57. if message:
  58. self.status['messages'] = [message]
  59. else:
  60. self.status['messages'] = []
  61. if status == 'error' and message:
  62. logger.error('Payment Terminal Error: '+message)
  63. elif status == 'disconnected' and message:
  64. logger.warning('Disconnected Terminal: '+message)
  65. def lockedstart(self):
  66. with self.lock:
  67. if not self.isAlive():
  68. self.daemon = True
  69. self.start()
  70. def push_task(self, task, data=None):
  71. self.lockedstart()
  72. self.queue.put((time.time(), task, data))
  73. def serial_write(self, text):
  74. assert isinstance(text, str), 'text must be a string'
  75. self.serial.write(text)
  76. def initialize_msg(self):
  77. max_attempt = 3
  78. attempt_nr = 0
  79. while attempt_nr < max_attempt:
  80. attempt_nr += 1
  81. self.send_one_byte_signal('ENQ')
  82. if self.get_one_byte_answer('ACK'):
  83. return True
  84. else:
  85. logger.warning("Terminal : SAME PLAYER TRY AGAIN")
  86. self.send_one_byte_signal('EOT')
  87. # Wait 1 sec between each attempt
  88. time.sleep(1)
  89. return False
  90. def send_one_byte_signal(self, signal):
  91. ascii_names = curses.ascii.controlnames
  92. assert signal in ascii_names, 'Wrong signal'
  93. char = ascii_names.index(signal)
  94. self.serial_write(chr(char))
  95. logger.debug('Signal %s sent to terminal' % signal)
  96. def get_one_byte_answer(self, expected_signal):
  97. ascii_names = curses.ascii.controlnames
  98. one_byte_read = self.serial.read(1)
  99. expected_char = ascii_names.index(expected_signal)
  100. if one_byte_read == chr(expected_char):
  101. logger.debug("%s received from terminal" % expected_signal)
  102. return True
  103. else:
  104. return False
  105. def prepare_data_to_send(self, payment_info_dict):
  106. amount = payment_info_dict['amount']
  107. if payment_info_dict['payment_mode'] == 'check':
  108. payment_mode = 'C'
  109. elif payment_info_dict['payment_mode'] == 'card':
  110. payment_mode = '1'
  111. else:
  112. logger.error(
  113. "The payment mode '%s' is not supported"
  114. % payment_info_dict['payment_mode'])
  115. return False
  116. cur_iso_letter = payment_info_dict['currency_iso'].upper()
  117. try:
  118. cur = pycountry.currencies.get(letter=cur_iso_letter)
  119. cur_numeric = str(cur.numeric)
  120. except:
  121. logger.error("Currency %s is not recognized" % cur_iso_letter)
  122. return False
  123. data = {
  124. 'pos_number': str(1).zfill(2),
  125. 'answer_flag': '0',
  126. 'transaction_type': '0',
  127. 'payment_mode': payment_mode,
  128. 'currency_numeric': cur_numeric.zfill(3),
  129. 'private': ' ' * 10,
  130. 'delay': 'A011',
  131. 'auto': 'B010',
  132. 'amount_msg': ('%.0f' % (amount * 100)).zfill(8),
  133. }
  134. return data
  135. def generate_lrc(self, real_msg_with_etx):
  136. lrc = 0
  137. for char in real_msg_with_etx:
  138. lrc ^= ord(char)
  139. return lrc
  140. def send_message(self, data):
  141. '''We use protocol E+'''
  142. ascii_names = curses.ascii.controlnames
  143. real_msg = (
  144. data['pos_number'] +
  145. data['amount_msg'] +
  146. data['answer_flag'] +
  147. data['payment_mode'] +
  148. data['transaction_type'] +
  149. data['currency_numeric'] +
  150. data['private'] +
  151. data['delay'] +
  152. data['auto'])
  153. logger.debug('Real message to send = %s' % real_msg)
  154. assert len(real_msg) == 34, 'Wrong length for protocol E+'
  155. real_msg_with_etx = real_msg + chr(ascii_names.index('ETX'))
  156. lrc = self.generate_lrc(real_msg_with_etx)
  157. message = chr(ascii_names.index('STX')) + real_msg_with_etx + chr(lrc)
  158. self.serial_write(message)
  159. logger.info('Message sent to terminal')
  160. def compare_data_vs_answer(self, data, answer_data):
  161. for field in [
  162. 'pos_number', 'amount_msg',
  163. 'currency_numeric', 'private']:
  164. if data[field] != answer_data[field]:
  165. logger.warning(
  166. "Field %s has value '%s' in data and value '%s' in answer"
  167. % (field, data[field], answer_data[field]))
  168. def parse_terminal_answer(self, real_msg, data):
  169. answer_data = {
  170. 'pos_number': real_msg[0:2],
  171. 'transaction_result': real_msg[2],
  172. 'amount_msg': real_msg[3:11],
  173. 'payment_mode': real_msg[11],
  174. 'currency_numeric': real_msg[12:15],
  175. 'private': real_msg[15:26],
  176. }
  177. logger.debug('answer_data = %s' % answer_data)
  178. self.compare_data_vs_answer(data, answer_data)
  179. return answer_data
  180. def get_answer_from_terminal(self, data):
  181. ascii_names = curses.ascii.controlnames
  182. full_msg_size = 1+2+1+8+1+3+10+1+1
  183. msg = self.serial.read(size=full_msg_size)
  184. logger.debug('%d bytes read from terminal' % full_msg_size)
  185. assert len(msg) == full_msg_size, 'Answer has a wrong size'
  186. if msg[0] != chr(ascii_names.index('STX')):
  187. logger.error(
  188. 'The first byte of the answer from terminal should be STX')
  189. if msg[-2] != chr(ascii_names.index('ETX')):
  190. logger.error(
  191. 'The byte before final of the answer from terminal '
  192. 'should be ETX')
  193. lrc = msg[-1]
  194. computed_lrc = chr(self.generate_lrc(msg[1:-1]))
  195. if computed_lrc != lrc:
  196. logger.error(
  197. 'The LRC of the answer from terminal is wrong')
  198. real_msg = msg[1:-2]
  199. logger.debug('Real answer received = %s' % real_msg)
  200. return self.parse_terminal_answer(real_msg, data)
  201. def transaction_start(self, payment_info):
  202. '''This function sends the data to the serial/usb port.
  203. '''
  204. payment_info_dict = simplejson.loads(payment_info)
  205. assert isinstance(payment_info_dict, dict), \
  206. 'payment_info_dict should be a dict'
  207. try:
  208. logger.debug(
  209. 'Opening serial port %s for payment terminal with baudrate %d'
  210. % (self.device_name, self.device_rate))
  211. # IMPORTANT : don't modify timeout=3 seconds
  212. # This parameter is very important ; the Telium spec say
  213. # that we have to wait to up 3 seconds to get LRC
  214. self.serial = Serial(
  215. self.device_name, self.device_rate,
  216. timeout=3)
  217. logger.debug('serial.is_open = %s' % self.serial.isOpen())
  218. if self.initialize_msg():
  219. data = self.prepare_data_to_send(payment_info_dict)
  220. if not data:
  221. return
  222. self.send_message(data)
  223. if self.get_one_byte_answer('ACK'):
  224. self.send_one_byte_signal('EOT')
  225. logger.info("Now expecting answer from Terminal")
  226. if self.get_one_byte_answer('ENQ'):
  227. self.send_one_byte_signal('ACK')
  228. self.get_answer_from_terminal(data)
  229. self.send_one_byte_signal('ACK')
  230. if self.get_one_byte_answer('EOT'):
  231. logger.info("Answer received from Terminal")
  232. except Exception, e:
  233. logger.error('Exception in serial connection: %s' % str(e))
  234. finally:
  235. if self.serial:
  236. logger.debug('Closing serial port for payment terminal')
  237. self.serial.close()
  238. def run(self):
  239. while True:
  240. try:
  241. timestamp, task, data = self.queue.get(True)
  242. if task == 'transaction_start':
  243. self.transaction_start(data)
  244. elif task == 'status':
  245. pass
  246. except Exception as e:
  247. self.set_status('error', str(e))
  248. driver = TeliumPaymentTerminalDriver()
  249. hw_proxy.drivers['telium_payment_terminal'] = driver
  250. class TeliumPaymentTerminalProxy(hw_proxy.Proxy):
  251. @http.route(
  252. '/hw_proxy/payment_terminal_transaction_start',
  253. type='json', auth='none', cors='*')
  254. def payment_terminal_transaction_start(self, payment_info):
  255. logger.debug(
  256. 'Telium: Call payment_terminal_transaction_start with '
  257. 'payment_info=%s', payment_info)
  258. driver.push_task('transaction_start', payment_info)