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="COM8",
    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'


z = 0 
g = 0 
step =-1 ;
alldata = ser.read()

from checksum_calculator import *


def checksum(msg):
    inputString = msg+CR+ETX
    outputString = inputString.encode('ascii').hex()
    return compute_checksum8_mod256(outputString)
count = 0
STX = '\x02'
ETX = '\x03'
ETB = '\x27'
EOT = '\x04'
ENQ = '\x05'
ACK = '\x06'
NAK = '\x25'
CR = '\r'
LF = '\n'
MOR = '>'
FS = '\x34'
GS = '\x35'
RS = '\x36'
SFS = '\x27'
VT = 0x0B; 

s1 = []
#s1.append ( STX + "1H|\\^&" + CR + ETX + checksum("1H|\\^&") + CR + LF)
#s1.append (  STX + "2P|1|||||||||||||^" + CR + ETX + checksum("2P|1|||||||||||||^") + CR + LF)
#s1.append (  STX + "3O|1|10008^1^2^1^N||^^^ALT|R|20090119100417|||||||||1||||||||||O" + CR + ETX + checksum("3O|1|10008^1^2^1^N||^^^ALT|R|20090119100417|||||||||1||||||||||O") + CR + LF)
#s1.append (  STX + "4O|2|10008^1^2^1^N||^^^AST|R|20090119100417|||||||||1||||||||||O" + CR + ETX + checksum("4O|2|10008^1^2^1^N||^^^AST|R|20090119100417|||||||||1||||||||||O") + CR + LF)
#s1.append ( STX + "5L|1|N" + CR + ETX + checksum("5L|1|N") + CR + LF)

link="http://api.naslab.gt4it.com/api/mispa-astm"
while True:
    #for line in ser.read():

        #print(ser.read(200))
        
        tdata = ser.read()           # Wait forever for anything
       
        if g ==1 :
           
                if(count == len(s1)):
                        print("ending data",EOT)
                        ser.write(b'\x04')
                        g = 0 
                        tdata = b''
                        s1.clear()
                if(count == -1):
                     ser.write(b'\x05')
                     count = 0
                     print("start sending ")
                     tdata = b''
                if(tdata == b'\x06'):
                    if count < len(s1):
                        print(tdata)
                        print("count === > ", count)
                        print("data ==> ",s1[count])
                        ser.write(str.encode(s1[count]))
                        count  = count + 1
                        tdata = b''
                    
               
        time.sleep(0.1)              # Sleep (or inWaiting() doesn't give the correct value)
        if tdata:
            if tdata == b'\x02'  or  tdata == b'\x05':
                    z=1
                    print(tdata)
                    print("here recive data")
                    ser.write(b'\x06')
              
            if tdata == b'\x04':
                z=0
                
               
                newdata = str(alldata.decode("utf-8"))
                print("all data  ===end ====> ",newdata)

                
                myobj = {'body':  newdata}
                x = requests.post(link, json = myobj , headers = {"Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJuYXMtbGFiIiwiYXVkIjoibmFzLWxhYiIsImp0aSI6ImZLb2tpeEw5UloiLCJpYXQiOjE3MDU2NTc5MjAuMjEzNjk1fQ.9N4Vi0cq5JFM4maBEKPCtElbLEtk3CHXQZJDtm1xECM"} )
                x = json.loads(x.text)
                
                print( x)  
                #ser.write(b'\x05')
                if("2Q|" in newdata):
                    print("found request")
                    for y in x['data']['requestResult']:
                        s1.append ( STX + y + CR + ETX + checksum(y) + CR + LF)
                        print("data insterted ==>" , y)
                    g=1
                    count = -1
                f = open('misba.txt','a')
                f.write(str(alldata) + "\n")
                f.close()

                alldata = ser.read()
                

                 
            
            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
            alldata += tdata
            
        
        
ser.close()
