#!/usr/bin/python
# isbdd - Iridium Short Burst Data Server
# Chris X Edwards <isbd@xed.ch>  - 2016-11-06

# Usage:
#     isbdd | tee ${SOMELOGFILE}
# What PID is listening?
#     lsof -i :65320

import isbd
import socket
from thread import *
import datetime
import Parser
import pyodbc
import time
OUTDIR= '/home/admin.warriertech/warriertech/SBD Project' # Obviously set this to make sense.
PORT= 65320  # 10800 is the normal port, but can be changed for dev testing.
HOST= ''     # Server interface to bind to. Blank is `INADDR_ANY`.
BACKLOG= 5  # Max connections on accept queue. See notes.
LOGQ= list() # Need a global queue so fast log posts don't garble each other.

def log(m):
    '''Log uses real "now" (arrival) time, not ISBD message or payload time.'''
    ts= datetime.datetime.now().strftime('%Y%m%dT%H%M%SZ') # ISO8601
    LOGQ.append( ts+':'+m ) # Append is a thread-safe operation.

# == Connection Handling For Each Thread ==
def servicethread(connection,mno,ip):
    Path= "/home/admin.warriertech/warriertech/SBD Project/Data.txt"
	
    f1=open(Path,'a')
    READ_BYTES= 2048 # Optimize per application.
    data= ''
    while True:
	f1=open(Path,'a')
        rdata= connection.recv(READ_BYTES)
	
        data+= rdata # This may not be necessary, but allows for huge messages.
		
        #print 'Connection said: %s' % data
        if not rdata:
            break
        M = isbd.Isbdmsg(data).unpack() 
	
	#print(M)
	list=[]
	list=M.parts_for_output()
	list1={}
	f1.write("\n")
	print(list)
	Message=Parser.SBD(list[12])
	IMEI_ID=int(list[0])
	list1=Message.display_parsed_data()
	print(list1)
	SQL(list1,IMEI_ID)
	data=''
        #M.write_sbd_file( M.dated_filename(OUTDIR,'-%06d'%mno) )
        #M.insert_in_mysql({'host':'sql.xed.ch','user':'xedtester','passwd':'xxxxxxxxx','db':'isbd_msg'})
        #M.insert_in_pgsql(con):
        #log( 'RECV:%s/%d,%s'%(ip[0],ip[1],M.log_entry()) )
    connection.close()
def SQL(list3,myIMEI_ID):
	
	server = 'warriertech-testsql.database.windows.net'
	database = 'WarrierTech-TestSQL'
	username = 'jiyetang'
	password = 'Tjy@7785153'
	driver= '{ODBC Driver 17 for SQL Server}'
	cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1443;DATABASE='+database+';UID='+username+';PWD='+ password)
	cursor = cnxn.cursor()
	IMEI=0
	#int(list[0])
	mytime=time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
	tsql= "INSERT INTO tbl_gps (IMEI,Latitude,Longitude,Year,Day,Hour,Minute,Supply_Voltage,ADC_Channel_2,ADC_Channel_3,GPIO_0_State,GPIO_1_State,Acc_X,Acc_y,Acc_Z,Acc_Temperature,Gyro_X,Gyro_Y,Gyro_Z,Time_Arrival) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"
	
	with cursor.execute(tsql,myIMEI_ID,list3[0][0],list3[0][1],list3[1][0],list3[1][1],list3[1][2],list3[1][3],list3[2][0],list3[3][0],list3[4][0],list3[5][0],list3[5][1],list3[6][0],list3[6][1],list3[6][2],list3[6][3],list3[7][0],list3[7][1],list3[7][2],mytime):
		print("Insert has been done")
		cnxn.commit()
# == Create Socket ==
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM) # I.E. (IPv4,UDP)
log( 'Socket Creation OK' )
# == Binding ==
try:
    # This line is to prevent "Bind failed! Address already in use (error #98)"
    # Which occurs if you restart the server too quickly.
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((HOST,PORT))
except socket.error as msg:
    log( 'ERROR: Bind failed! %s (error #%s)' % (msg[1],str(msg[0])) )
    s.close()
    raise SystemExit
log('Socket Binding OK')
# == Listening ==
s.listen(BACKLOG)
log('Socket Listening on %d OK' % PORT)
# == Client Transaction ==
msg_num= int(0)
while True:
    while len(LOGQ): # Clear out queue log, i.e. don't write log concurrently.
        print LOGQ.pop(0)
    try:
        msg_num= (msg_num+1)%1e6 # Reset to 0 after a million.
        conn,addr= s.accept()
        #log( 'Connected to %s:%d' % addr )
        start_new_thread(servicethread, (conn,msg_num,addr) )
    except KeyboardInterrupt:
        break
s.close()
log('Socket Closed OK')