import brainstem
from brainstem import _BS_C #Gives access to aProtocolDef.h constants. 
from brainstem.pd_channel_logger import PDChannelLogger
from brainstem.result import Result
from brainstem.stem import USBHub3c

import time
import sys

LOOPS = 25

#Get one packet at a time.
def proccess_packets_one_at_a_time(logger):
    #Pull packets until we get an error
    result = logger.getPacket()
    while result.error == Result.NO_ERROR:
        print(result.value)
        result = logger.getPacket()



#Get all available packets in single call. 
#Note: Packet count is limited up to the default parameter buffer_length
def proccess_multiple_packets_at_a_time(logger):
    #Get available packets.
    result = logger.getPackets()
    if result.error == Result.NO_ERROR:
        print(result.value)


#Main application. 
if __name__ == '__main__':

    stem = brainstem.stem.USBHub3c()
    connect_result = stem.discoverAndConnect(1)
    if connect_result != Result.NO_ERROR:
        print("Could not find and connect to a USBHub3c. Exiting (Error: %d)" % connect_result)
        sys.exit(1)

    #Create a PDChannelLogger for each port
    loggers = list()
    for x in range(0, USBHub3c.NUMBER_OF_POWER_DELIVERY_PORTS):
        loggers.append(PDChannelLogger(stem, x))

    for l in loggers:
        err = l.setEnabled(True) #Enable
        if err != Result.NO_ERROR:
            if err == Result.PERMISSION_ERROR:
                print("This USBHub3c does not have the PD Logger Feature T99-PD-LOG")
            exit(err)

        #Attempt to trigger PD communication on every port.
        #Note: No traffic will occur if the devices does not support PD.
        stem.pd[l.index].request(_BS_C.pdRequestRemoteSourcePowerDataObjects)

    time.sleep(2) #Wait for messages to come in.

    for l in loggers:
        print("Port: %d" % (l.index))
        print("Processing BrainStem Power Delivery Packets one at a time.")
        proccess_packets_one_at_a_time(l);

    for l in loggers:
        #Attempt to trigger PD communication on every port.
        #Note: No traffic will occur if the devices does not support PD.
        stem.pd[l.index].request(_BS_C.pdRequestRemoteSourcePowerDataObjects)

    time.sleep(2) #Wait for messages to come in.

    for l in loggers:
        print("Port: %d" % (l.index))
        print("Processing multiple BrainStem Power Delivery Packets at a time.")
        proccess_multiple_packets_at_a_time(l)
        l.setEnabled(False) #Disable PD Logging
        

    stem.disconnect()


