#!/usr/bin/env ruby

require 'socket'
require 'influxdb'
require 'gis/distance'

HOSTNAME = IO::readlines("/proc/sys/kernel/hostname").join.chomp
INTERVAL = 1
SERIES = 'adsb'
POS = [ 51.08102, 13.72806 ]

db = InfluxDB::Client.new(url: "http://grafana.serv.zentralwerk.org:8086/adsb")
msg_type_count = {}

sock = TCPSocket.new "radiobert.serv.zentralwerk.org", 30003
STDERR.puts "Connected to dump1090"

while line = sock.gets
  begin
    fields = line.chomp.split(/,/)
    msg_type = fields[1].to_i
    msg_type_count[msg_type] = 0 unless msg_type_count[msg_type]
    aircraft = fields[4]
    points = [ { series: SERIES,
                 tags: {
                   data: "msg_type",
                   msg_type: msg_type,
                 },
                 values: {
                   count: msg_type_count[msg_type] += 1,
                 },
               } ]

    case msg_type
    when 3
      values = {}
      unless fields[14].empty? or fields[15].empty?
        values[:lat] = fields[14].to_f
        values[:lon] = fields[15].to_f
        values[:dist] = GIS::Distance::new(POS[0], POS[1], values[:lat], values[:lon]).distance
      end
      unless fields[11].empty?
        values[:alt] = fields[11].to_i
      end

      points.push({ series: SERIES,
                    tags: {
                      data: "pos",
                      aircraft: aircraft,
                    },
                    values: values,
                  })
    when 4
      values = {}
      unless fields[12].empty?
        values[:ground_speed] = fields[12].to_i
      end
      unless fields[13].empty?
        values[:track] = fields[13].to_i
      end
      points.push({ series: SERIES,
                    tags: {
                      data: "velocity",
                      aircraft: aircraft,
                    },
                    values: values,
                  })
    end

    db.write_points points, 'm'

  rescue
    STDERR.puts $!
  end
end
