Last Updated: February 25, 2016
·
1.445K
· jrichter

Ruby HL7 Listener

I needed to see what a service at the hospital I work at was sending. This little snippet of code sets up a tcp server and listens for incoming connections. When it gets an HL7 message, it sends an ACK and saves the message to a file. That way you can see exactly what your getting!

require 'thread'
require 'socket'

server = TCPServer.new(3003)

puts "Listening on port 3003"

while true
  Thread.new(server.accept) do |client|
    #raw = client.readlines # This is slooooow
    begin
      raw = client.recvfrom(1024) # Cut off after 1mb
      msg_control_id = raw.first.split(/\|/)[9]
      ack = "\xbMSH|^~\\&|your_ae||their_ae||#{Time.now.strftime("%Y%m%d%H%M%S")}||ACK|#{rand(10000)}|P|2.3|\xdMSA|AA|#{msg_control_id}|\xd\x1c\xd"
      client.puts ack.force_encoding("ISO-8859-1") # force encoding
      client.close
    rescue => e
      puts e.message
    end
    if raw != nil
      file = File.open("hl7.txt", 'a+')
      puts "received.. #{raw}"
      file.puts(raw.to_s.force_encoding("ISO-8859-1")) # dump the msg
      file.puts("Split")
      raw.each do |line| # Split the msg and display
        line.split(/\r/).each do |segment|
          file.puts(segment)
        end
      end
      file.close
    end
  end
end