Example #1
0
 def __init__(self, DeviceId=None ):
     '''
         Queue interfaces for messaging
     '''
     self.dbi = AndruinoDb()
     if not DeviceId:
         print "[API] DeviceId required. Please set device ID "
         sys.exit()
     else:
         '''
             Set Device ID for this implementation of the API
         '''
         self.device_id=DeviceId
     
     
     '''
         Create messaging queues for interacting with the threads.
     '''
     self.serialQueue = Queue(0)
     self.emailQueue = Queue(0)
     '''
         Stub for accessing thread
     '''
     self.serialThread = None
     self.emailThread = None
     '''
Example #2
0
    def __init__(self, SerialInterfaceQueue, device_id, deviceType='arduino'):
        ''' 
            Setup serial interface
            
            readSleepInterval - This is the amount of time the thread will wait before 
                            sending a read instruction to the AVR and return the result.
                            Each read operation will pull the state of the device from the AVR
                            and store the response in the database. 
                            In debug mode, thread will display raw output to the screen.
            QueuePollInterval - Amount of time tread will wait before checking for messages 
                            on the serialInterfaceQueue...    
        '''
        ready_sleep_timeout = 20
        self.map = deviceMap(deviceType)
        self.pinMap = self.map.getPinMap()
        self.dbi = AndruinoDb()
        self.ReadSleepTime = 10
        
        self.QueuePollInterval = 0.5
        self.serialQueue = SerialInterfaceQueue
        self.device_id = device_id
        self.emailSettings = {}
        '''
            Initialize this thread
        '''
        
        
        self.ThreadRunState = 0
        self.ThreadRunStatus = False
        threading.Thread.__init__(self)
        self.StopMe = threading.Event()
        
        device_port = self.dbi.getDeviceById(self.device_id)
        
        # setup the serial port
        try:
            self.ser = serial.Serial(device_port['port'], 115200, timeout=0.25)
        except serial.SerialException:
            '''
                If port can not be opened...
            '''
            print """Failed to open port [%s]\nCheck your configuration and try again""" % device_port['port']
            sys.exit(2)
            
        # Wait for the serial post to initialize
        print "Thread is sleeping before starting..."
        time.sleep(ready_sleep_timeout)

        self.serialMsg = {
            'ID':None,
            'TYPE': None,
            'DATA': None
        }
Example #3
0
class AndruinoApi():
    def __init__(self, DeviceId=None ):
        '''
            Queue interfaces for messaging
        '''
        self.dbi = AndruinoDb()
        if not DeviceId:
            print "[API] DeviceId required. Please set device ID "
            sys.exit()
        else:
            '''
                Set Device ID for this implementation of the API
            '''
            self.device_id=DeviceId
        
        
        '''
            Create messaging queues for interacting with the threads.
        '''
        self.serialQueue = Queue(0)
        self.emailQueue = Queue(0)
        '''
            Stub for accessing thread
        '''
        self.serialThread = None
        self.emailThread = None
        '''
            Map Pins to Port Interfaces
            Map must be maintained at this level for multiple device support.
        ''' 
        
              
    def startSerial(self, ):
        '''
            Start the serial thread for this device
            thread will be bound to the serial interface defined within the devices table
            All calls to the thread interfaces will be bound to a unique device 
        '''
        self.serialThread = AndrSerial(self.serialQueue, self.device_id)
        self.serialThread.start()
        
        '''
            Place Messages in queue to set device configuration base
            on config data from the database.
            Note: Threads are bound to a particular device_id. So id 
            does not need to be set. 
        '''
        self.writeConfig()

        
        # TODO 
        '''
            Add interface for starting email thread...
        '''
        
        
    def stopSerial(self):
        self.serialThread.stop()
        
        
    def setOutput(self, pinNumber, pinState):
        '''
            This method is used to set 
            Set ouput state of a pin attached to the avr controller
            Pin Numbers = 2-13 (0 & 1 reserved for serial communication)
            Pin State = 0 or 1 
            THIS SECTION SUPPORTS PORT INTERFACE ONLY (Change IO) 
            TODO: Add multiple devices (Phase 2)
        '''
        
        
        #self.serialThread.setOutput(pinNumber,pinState)
        '''
            Cross reference from Ports to Hex commands
        '''
        
        msg = {
               'ID': int(time.time()),
               'TYPE': 'WRITE',
               'DATA': "%s:%s" % (pinNumber, pinState),
               'STATE': pinState
        }
        self.serialQueue.put(msg)

    def setConfig(self, pinNumber, pinMode):
        '''
            This method is used to set 
            Set ouput state of a pin attached to the avr controller
            Pin Numbers = 2-13 (0 & 1 reserved for serial communication)
            Pin State = 0 or 1 
            THIS SECTION SUPPORTS PORT INTERFACE ONLY (Change IO) 
            TODO: Add multiple devices (Phase 2)
        '''
        
        
        #self.serialThread.setOutput(pinNumber,pinState)
        '''
            Cross reference from Ports to Hex commands
        '''
        
        msg = {
               'ID': int(time.time()),
               'TYPE': 'CFG',
               'DATA': "%s:%s" % (pinNumber, pinMode)
        }
        self.serialQueue.put(msg)

    def writeOutput(self, DetailId, Value):
        '''
            Requires DetailId...
            Read state from the database 
        '''
        ConfigSettings = self.dbi.getConfig(DetailId)
        intValue = int(Value)
        for Setting in ConfigSettings:
            self.setOutput(Setting['pin'], intValue)

    def writeConfig(self, DetailId=None):
        '''
            Write the pin config data to the database.
            
            One Parameter
            DetailId - Represents the Pin stored as id in the details table.
            When DetailId is set only that device will be written to the serial interface
            
            if the parameter DetailId is not passed in, value defaults to None.
            In this condition, all devices within self.DeviceId will be initialized. 
            
        '''
        ConfigSettings = self.dbi.getConfig(DetailId)
        for Setting in ConfigSettings:
            '''
                Process all rows returned from database
                run config on each row. 
                
                If DetailId is set only one row will be returned
            '''
            print "Settings Pin %s - Config %s" % (Setting['pin'], Setting['config'])
            self.setConfig(Setting['pin'], Setting['config'])
        
        
        
        

    def getAvrMap(self):
        '''
            Get the IO map from the thread
            returns dictionary of ports and OI states
        '''
        return self.serialThread.getMap()
Example #4
0
class AndrSerial(threading.Thread):
    
    def __init__(self, SerialInterfaceQueue, device_id, deviceType='arduino'):
        ''' 
            Setup serial interface
            
            readSleepInterval - This is the amount of time the thread will wait before 
                            sending a read instruction to the AVR and return the result.
                            Each read operation will pull the state of the device from the AVR
                            and store the response in the database. 
                            In debug mode, thread will display raw output to the screen.
            QueuePollInterval - Amount of time tread will wait before checking for messages 
                            on the serialInterfaceQueue...    
        '''
        ready_sleep_timeout = 20
        self.map = deviceMap(deviceType)
        self.pinMap = self.map.getPinMap()
        self.dbi = AndruinoDb()
        self.ReadSleepTime = 10
        
        self.QueuePollInterval = 0.5
        self.serialQueue = SerialInterfaceQueue
        self.device_id = device_id
        self.emailSettings = {}
        '''
            Initialize this thread
        '''
        
        
        self.ThreadRunState = 0
        self.ThreadRunStatus = False
        threading.Thread.__init__(self)
        self.StopMe = threading.Event()
        
        device_port = self.dbi.getDeviceById(self.device_id)
        
        # setup the serial port
        try:
            self.ser = serial.Serial(device_port['port'], 115200, timeout=0.25)
        except serial.SerialException:
            '''
                If port can not be opened...
            '''
            print """Failed to open port [%s]\nCheck your configuration and try again""" % device_port['port']
            sys.exit(2)
            
        # Wait for the serial post to initialize
        print "Thread is sleeping before starting..."
        time.sleep(ready_sleep_timeout)

        self.serialMsg = {
            'ID':None,
            'TYPE': None,
            'DATA': None
        }
        
        
    def run(self):
        '''
            Start the Serial thread
        '''
        self.ThreadRunState = 1
        self.initAvr()
        
        '''
            Wait until the controller is ready
        '''
        
        
        while self.ThreadRunState:
            '''
                do this alot
            '''
            self.ThreadRunStatus = True
            '''
                Read data from the AVR
            '''
            try:
                self.readAvr()
            except serial.SerialException, why:
                print "Failed to read from device: %s" %(why)
                sys.exit(2)
            
            '''
                UnComment to print debug map
            '''
            #self.printMap()
            
            
            '''
                Sleep for a period of time before starting up again...
            '''
            waitTime = math.ceil(self.ReadSleepTime / self.QueuePollInterval)
            waitTime = int(waitTime)
            #print "Going to scan %s times" % (str(waitTime))
            for s in range(1 , waitTime):
                msg = self.getMsg() 
                if msg != None:
                    '''
                        Do something if a message is on the queue
                    '''
                    print "Got a message -> %s " % (msg)
                    self.parseMsg(msg)
                time.sleep(self.QueuePollInterval)
        
        '''
            Thread looping finished 
            Clean up and exit program
        '''
        self.cleanup()