import serial
import time
import binascii
import requests
import json


#dencoded_byte = byte.encode('hex')

# f = open("setting.txt", "r")
# print(f.read())

                
ser = serial.Serial(
    port="COM2",
    baudrate=9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=0
)
print("connected to: " + ser.portstr)




url = 'http://api.naslab.gt4it.com/api/maglumi-astm'

z = 0 
datamain = [] 

while True:
    #for line in ser.read():

        #print(ser.read(200))
       
        
        tdata = ser.read()           # Wait forever for anything
       #
        time.sleep(0.4)              # Sleep (or inWaiting() doesn't give the correct value)
        #print (tdata)
        #ser.inWaiting()
        if tdata:
            print(tdata)
            if tdata == b'\x05':
               
                print("here recive data")
                ser.write(b'\x06')
            if tdata == b'\x06' and z==1:
                z=0
                for y in datamain:
                    print(y , "<<=== data inquery====")
                    ser.write(b'\x02')                      
                    ser.write(bytes(y, 'utf-8'))
                    ser.write(b'\x0D')
                    ser.write(b'\x03')    
                ser.write(b'\x04')
            
            else:
                if (tdata != b'\x05' and  tdata != b'\x06') :
                    data_left = ser.inWaiting()  # Get the number of characters ready to be read
                    tdata += ser.read(data_left) # Do the read and combine it with the first character
                    f = open('dataFile.txt','a')
                    newdata = str(tdata.decode("utf-8"))
                    myobj = {'body':  newdata}
                    print(myobj)    
                    x = requests.post(url, json = myobj , headers = {"Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJuYXMtbGFiIiwiYXVkIjoibmFzLWxhYiIsImp0aSI6ImZLb2tpeEw5UloiLCJpYXQiOjE3MDU2NTc5MjAuMjEzNjk1fQ.9N4Vi0cq5JFM4maBEKPCtElbLEtk3CHXQZJDtm1xECM"} )
                    x = json.loads(x.text)
                    print( x)                   
                    if x['success']:
                    #if True:
                           
                            #print(x['data']['requestType'],"<<<<<-====== request type")
                            if x['data']['requestType'] == "inquiry":
                                ser.write(b'\x05')
                                print("inquerry sucess now ?????")
                                datamain = x['data']['requestResult']                               
                                z=1
                            else:
                                print(x['data'] , "<<===else====")
                       
                    else:
                        print("fail")
             
                    f.write(newdata)    # Appends output to file
                    print(tdata)
                    if(tdata.decode("utf-8").endswith("\x05")):
                        print("found multi data ====== > ")
                        ser.write(b'\x06')
                    
                    #ser.write(b'\x05')
                    f.close()
        
ser.close()
