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.

197 lines
6.1 KiB

7 years ago
10 years ago
  1. #! /usr/bin/python3
  2. from serial import Serial
  3. import curses.ascii
  4. import time
  5. import pycountry
  6. DEVICE = '/dev/ttyACM0'
  7. DEVICE_RATE = 9600
  8. PAYMENT_MODE = 'card' # 'card' or 'check'
  9. CURRENCY_ISO = 'EUR'
  10. AMOUNT = 12.42
  11. def serial_write(serial, text):
  12. assert isinstance(text, str), 'text must be a string'
  13. serial.write(text.encode('ascii'))
  14. def initialize_msg(serial):
  15. max_attempt = 3
  16. attempt_nr = 0
  17. while attempt_nr < max_attempt:
  18. attempt_nr += 1
  19. send_one_byte_signal(serial, 'ENQ')
  20. if get_one_byte_answer(serial, 'ACK'):
  21. return True
  22. else:
  23. print("Terminal : SAME PLAYER TRY AGAIN")
  24. send_one_byte_signal(serial, 'EOT')
  25. # Wait 1 sec between each attempt
  26. time.sleep(1)
  27. return False
  28. def send_one_byte_signal(serial, signal):
  29. ascii_names = curses.ascii.controlnames
  30. assert signal in ascii_names, 'Wrong signal'
  31. char = ascii_names.index(signal)
  32. serial_write(serial, chr(char))
  33. print('Signal %s sent to terminal' % signal)
  34. def get_one_byte_answer(serial, expected_signal):
  35. ascii_names = curses.ascii.controlnames
  36. one_byte_read = serial.read(1).decode('ascii')
  37. expected_char = ascii_names.index(expected_signal)
  38. if one_byte_read == chr(expected_char):
  39. print("%s received from terminal" % expected_signal)
  40. return True
  41. else:
  42. return False
  43. def prepare_data_to_send():
  44. if PAYMENT_MODE == 'check':
  45. payment_mode = 'C'
  46. elif PAYMENT_MODE == 'card':
  47. payment_mode = '1'
  48. else:
  49. print("The payment mode '%s' is not supported" % PAYMENT_MODE)
  50. return False
  51. cur_iso_letter = CURRENCY_ISO.upper()
  52. try:
  53. cur = pycountry.currencies.get(alpha_3=cur_iso_letter)
  54. cur_numeric = str(cur.numeric)
  55. except:
  56. print("Currency %s is not recognized" % cur_iso_letter)
  57. return False
  58. data = {
  59. 'pos_number': str(1).zfill(2),
  60. 'answer_flag': '0',
  61. 'transaction_type': '0',
  62. 'payment_mode': payment_mode,
  63. 'currency_numeric': cur_numeric.zfill(3),
  64. 'private': ' ' * 10,
  65. 'delay': 'A011',
  66. 'auto': 'B010',
  67. 'amount_msg': ('%.0f' % (AMOUNT * 100)).zfill(8),
  68. }
  69. return data
  70. def generate_lrc(real_msg_with_etx):
  71. lrc = 0
  72. for char in real_msg_with_etx:
  73. lrc ^= ord(char)
  74. return lrc
  75. def send_message(serial, data):
  76. '''We use protocol E+'''
  77. ascii_names = curses.ascii.controlnames
  78. real_msg = (
  79. data['pos_number'] +
  80. data['amount_msg'] +
  81. data['answer_flag'] +
  82. data['payment_mode'] +
  83. data['transaction_type'] +
  84. data['currency_numeric'] +
  85. data['private'] +
  86. data['delay'] +
  87. data['auto'])
  88. print('Real message to send = %s' % real_msg)
  89. assert len(real_msg) == 34, 'Wrong length for protocol E+'
  90. real_msg_with_etx = real_msg + chr(ascii_names.index('ETX'))
  91. lrc = generate_lrc(real_msg_with_etx)
  92. message = chr(ascii_names.index('STX')) + real_msg_with_etx + chr(lrc)
  93. serial_write(serial, message)
  94. print('Message sent to terminal')
  95. def compare_data_vs_answer(data, answer_data):
  96. for field in [
  97. 'pos_number', 'amount_msg',
  98. 'currency_numeric', 'private']:
  99. if data[field] != answer_data[field]:
  100. print(
  101. "Field %s has value '%s' in data and value '%s' in answer"
  102. % (field, data[field], answer_data[field]))
  103. def parse_terminal_answer(real_msg, data):
  104. answer_data = {
  105. 'pos_number': real_msg[0:2],
  106. 'transaction_result': real_msg[2],
  107. 'amount_msg': real_msg[3:11],
  108. 'payment_mode': real_msg[11],
  109. 'currency_numeric': real_msg[12:15],
  110. 'private': real_msg[15:26],
  111. }
  112. print('answer_data = %s' % answer_data)
  113. compare_data_vs_answer(data, answer_data)
  114. return answer_data
  115. def get_answer_from_terminal(serial, data):
  116. ascii_names = curses.ascii.controlnames
  117. full_msg_size = 1+2+1+8+1+3+10+1+1
  118. msg = serial.read(size=full_msg_size).decode('ascii')
  119. print('%d bytes read from terminal' % full_msg_size)
  120. assert len(msg) == full_msg_size, 'Answer has a wrong size'
  121. if msg[0] != chr(ascii_names.index('STX')):
  122. print('The first byte of the answer from terminal should be STX')
  123. if msg[-2] != chr(ascii_names.index('ETX')):
  124. print('The byte before final of the answer '
  125. 'from terminal should be ETX')
  126. lrc = msg[-1]
  127. computed_lrc = chr(generate_lrc(msg[1:-1]))
  128. if computed_lrc != lrc:
  129. print('The LRC of the answer from terminal is wrong')
  130. real_msg = msg[1:-2]
  131. print('Real answer received = %s' % real_msg)
  132. return parse_terminal_answer(real_msg, data)
  133. def transaction_start():
  134. '''This function sends the data to the serial/usb port.
  135. '''
  136. serial = False
  137. try:
  138. print(
  139. 'Opening serial port %s for payment terminal with '
  140. 'baudrate %d' % (DEVICE, DEVICE_RATE))
  141. # IMPORTANT : don't modify timeout=3 seconds
  142. # This parameter is very important ; the Telium spec say
  143. # that we have to wait to up 3 seconds to get LRC
  144. serial = Serial(
  145. DEVICE, DEVICE_RATE, timeout=3)
  146. print('serial.is_open = %s' % serial.isOpen())
  147. if initialize_msg(serial):
  148. data = prepare_data_to_send()
  149. if not data:
  150. return
  151. send_message(serial, data)
  152. if get_one_byte_answer(serial, 'ACK'):
  153. send_one_byte_signal(serial, 'EOT')
  154. print("Now expecting answer from Terminal")
  155. if get_one_byte_answer(serial, 'ENQ'):
  156. send_one_byte_signal(serial, 'ACK')
  157. get_answer_from_terminal(serial, data)
  158. send_one_byte_signal(serial, 'ACK')
  159. if get_one_byte_answer(serial, 'EOT'):
  160. print("Answer received from Terminal")
  161. except Exception as e:
  162. print('Exception in serial connection: %s' % str(e))
  163. finally:
  164. if serial:
  165. print('Closing serial port for payment terminal')
  166. serial.close()
  167. if __name__ == '__main__':
  168. transaction_start()