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.

296 lines
11 KiB

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