## Serial link software:: ---------------------------------------------

def serInitialization():
    #activate the serial port, if possible
    try:
        ser = serial.Serial('COM6', 9600, timeout=1) #initialize the serial port
        return ser
    except:
        print "Error: serial port cannot be initialized"
        while(1):
            voidholder = 1

ser = serInitialization()
global timeOut
global Fanstate
global O2state
global fuelCount
global Tnaught
global dataB
timeOut = 0

def receive():
    global timeOut #serial receipt timeout in case of timing conflicts
    try:
        data = int(ser.readline()) #try and receive data 
        return data
    except:
        if timeOut == 5:
            return 9999 #return null code for timeout

def transmit(command,data,address):
    global timeOut
    #three byte control protocol
    ser.write(chr(255)) #sends the watch byte
    ser.write(chr(command)) #sends the control byte
    ser.write(chr(data)) #sends the payload data
    ser.write(chr(address)) #additional 'address' byte in case the command requires 2 inputs
    while receive() != 9999: #waits until command receipt is acknowledged
        print "trap"
        timeOut = timeOut + 1
        voidholder = 1
    timeOut = 0
    return

def test():
    #test function for atomized control commands
    n = 0
    while n < 10:
        digitalWrite(11,1) #pin 11 high
        time.sleep(.1)
        digitalWrite(11,0) #pin 11 low
        time.sleep(.1)
        print analogRead() #read analog 0
        analogWrite(11,n) #write PWM to 11
        time.sleep(.1)
        print digitalRead(12) #digital read 12
        n = n + 1

def digitalWrite(pin,value):
    #triggers a digital write on pin to 1==HIGH 0==LOW
    if value == 1:
        transmit(100,pin,0) #send chr(100) (writeHIGH) and pin data
    elif value == 0:
        transmit(101,pin,0) #send chr(101) (writeLOW) and pin data
    return receive() #all controls transmit SOME data, so all atomized controls need a final receipt  

def analogRead():
    transmit(10,0,0) #send chr(10) (analogREAD)
    return receive() #return raw analogRead() data

def digitalRead(pin):
    transmit(99,pin,0) #send chr(99) (digitalREAD) and pin data
    return receive()

def analogWrite(pin,value):
    transmit(11,value,pin) #send chr(11) (analogWRITE), pin data, and PWM value (scaled 0-255)
    return receive()

def servo(pos):
    transmit(55,pos,0)
    return receive()

##End serial link software:: ---------------------------------------------