from __future__ import division
import time
import struct
import sys

ifile = "./telemetry.csv"

arguments = sys.argv

print arguments

ifile = arguments[1]
ofile = arguments[2]

i = open(ifile,"r")
o = open(ofile,"w")

o.write("tag,msg_type,msg_rev,time,epoch,lat,lon,activity,hdop,speed,alt,battery,solar_ma,temp,ttff,crc\n")

def twos_complement(hexstr,bits):
     value = int(hexstr,16)
     if value & (1 << (bits-1)):
         value -= 1 << bits
     return value

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False


while 1==1:
  data = i.readline()
  if data == "": break
  try:
    check = data.split(",")[0]
  except:
    continue
  if is_number(check) == False: continue
  result = data.split(",")[2]

# result = "00001F5D00009CD90260C2C31B42F7E395C2DC0000007200001F009C01001103DCB755555557F9FA"


  tag = result[0:8]
  msg_type = result[8:10]
  msg_rev = result[10:12]
  epoch = result[12:20]
  lat_float = result[20:28]
  lon_float = result[28:36]
  activity = result[36:44]
  hdop = result[44:48]
  speed = result[48:50]
  alt = result[50:54]
  battery = result[54:58]
  solar_ma = result[58:60]
  temp_signed = result[60:62]
  ttff = result[62:64]
  crc = result[64:66]

  msg_type = str(int(msg_type,16))
  msg_rev = str(int(msg_rev,16))
  newepoch = epoch[6:8]+epoch[4:6]+epoch[2:4]+epoch[0:2]
  calctime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(newepoch,16)))
  newepoch = str(int(newepoch,16))
  lon_float = lon_float[6:8]+lon_float[4:6]+lon_float[2:4]+lon_float[0:2]
  lat_float = lat_float[6:8]+lat_float[4:6]+lat_float[2:4]+lat_float[0:2]
  lat = str(struct.unpack('!f', lat_float.decode('hex'))[0])
  lon = str(struct.unpack('!f', lon_float.decode('hex'))[0])
  activity = str(int(activity[6:8]+activity[4:6]+activity[2:4]+activity[0:2],16))  
  hdop = str(int(hdop[2:4]+hdop[0:2],16)/100)
  speed = str(int(speed,16))
  alt = str(twos_complement(alt[2:4]+alt[0:2],16))
  battery = str(int(battery[2:4]+battery[0:2],16)/100)
  solar_ma = str(int(solar_ma[2:4]+solar_ma[0:2],16))
  temp = str(twos_complement(temp_signed,8))
  ttff = str(int(ttff,16))

#    struct TelemetryRev0_t {
#        uint8_t address[4];
#        uint8_t message_type;
#        uint8_t message_rev;
#        uint32_t time;
#        float latitude;
#        float longitude;
#        uint32_t activity;
#        uint16_t hdop;
#        uint8_t speed;
#        int16_t altitude;
#        uint16_t battery;
#        uint8_t solar_current_ma;
#        int8_t temperature_c;
#        uint8_t ttff;
#        uint16_t crc;
#
#    }__attribute__ ((packed));

  o.write(tag+","+msg_type+","+msg_rev+","+calctime+","+newepoch+","+lat+","+lon+","+activity+","+hdop+","+speed+","+alt+","+battery+","+solar_ma+","+temp+","+ttff+","+crc+"\n")

i.close()
o.close()


