ea-ps_2084-03b/mitm.rb

53 lines
1.6 KiB
Ruby
Raw Normal View History

2015-05-26 20:32:29 +02:00
#!/usr/bin/env ruby
# encoding: utf-8
2015-07-30 08:21:20 +02:00
# ruby: 1.9
2015-05-26 20:32:29 +02:00
require 'serialport'
require './telegram'
pc_serial = SerialPort.open("/dev/ttyUSB0",{ baud: 57600, databits: 8, parity: SerialPort::ODD, stop_bit: 1, flow_control: SerialPort::NONE})
ps_serial = SerialPort.open("/dev/ttyACM0",{ baud: 115200, databits: 8, parity: SerialPort::ODD, stop_bit: 1, flow_control: SerialPort::NONE})
2015-07-30 08:55:41 +02:00
# ensure serial settings (weird bug)
2015-08-24 16:12:30 +02:00
# the different baudrates used
baudrates = []
baudrates << {baud: 57600, parity: SerialPort::ODD}
baudrates << {baud: 115200, parity: SerialPort::ODD}
baudrate_i = 0
2015-07-30 08:55:41 +02:00
2015-05-26 20:32:29 +02:00
while true
activities = IO.select([pc_serial,ps_serial])
activities[0].each do |activity|
2015-08-24 16:12:30 +02:00
data = activity.readpartial(1024)
2015-05-26 20:32:29 +02:00
line = data.unpack("C*").collect { |b| sprintf("%02X ",b) }.join
if activity==pc_serial then
puts "pc->ps: "+line
2015-07-30 08:57:00 +02:00
begin
telegram = Telegram.parse(data)
2015-08-24 16:12:30 +02:00
if telegram then
puts "pc->ps: "+telegram.to_s if telegram
ps_serial.write(data)
else
baudrate_i = (baudrate_i+1)%baudrates.size
pc_serial.baud = baudrates[baudrate_i][:baud]
pc_serial.parity = baudrates[baudrate_i][:parity]
puts "could not parse message: switching baudrate to #{pc_serial.baud} bps"
end
2015-07-30 08:57:00 +02:00
rescue Exception => e
puts e.to_s
end
2015-05-26 20:32:29 +02:00
elsif activity==ps_serial then
puts "ps->pc: "+line
2015-07-30 08:57:00 +02:00
begin
telegram = Telegram.parse(data)
puts "ps->pc: "+telegram.to_s if telegram
rescue Exception => e
puts e.to_s
end
2015-05-26 20:32:29 +02:00
pc_serial.write(data)
else
raise "unknown source"
end
end
end