import pyModeS as pms
from pyModeS.extra.tcpclient import TcpClient

# define your custom class by extending the TcpClient
#   - implement your handle_messages() methods
class ADSBClient(TcpClient):
	def __init__(self, host, port, rawtype):
		super(ADSBClient, self).__init__(host, port, rawtype)

	def handle_messages(self, messages):
		for msg, ts in messages:
			#print("Length", len(msg))
			#print(msg)

			cs = ''

			df = pms.df(msg)
			#print(df , msg)

			if len(msg) != 28:  # wrong data length
				continue

			if df != 17:  # not ADSB
				#print("Not ADSB Data")
				continue

			if pms.crc(msg) !=0:  # CRC fail
				print("Crc failed")
				continue

			#icao = pms.adsb.icao(msg)
			tc = pms.adsb.typecode(msg)
            
			if ((tc >=1) and (tc <= 4)):
				cs = pms.adsb.callsign(msg)
				cat = pms.adsb.category(msg)
				#print( cs,cat,msg)
				mList = [ " "+ str(cs).replace("_"," "),str(cat),str(msg)]
				print (",".join(mList))

			#cs = pms.decoder.bds.bds08.callsign(msg)

			# TODO: write you magic code here
			# print(ts, icao, tc, msg)
			#print(pms.commb.cs20(msg))
			#print(tc)

# run new client, change the host, port, and rawtype if needed
#client = ADSBClient(host='192.168.25.10', port=30005, rawtype='beast')
client = ADSBClient(host='192.168.25.50', port=30002, rawtype='raw')
try:
	client.run()
except ValueError:
	print("ooops", ValueError)