Example #1
0
    def EnableSensor(self, sensor, enable):
        """Enable a sensor/actuator

        Args:
            sensor: Hash composed from name and device class/type
            enable: 1 to enable, 0 to disable

        Returns:
            True for success, False otherwise.
        """
        info('Enable sensor: ' + str(sensor) + ' ' + str(enable))
        try:
            if sensor is None:
                return False
            if enable is None:
                return False
            with self.sensorMutex:
                if enable == 0:
                    #add item to the list
                    if sensor not in self.disabledSensors:
                        DbManager.Insert(self.disabledSensorTable, sensor)
                        self.disabledSensors[sensor] = 1
                else:
                    #remove item from the list
                    if sensor in self.disabledSensors:
                        DbManager.Delete(self.disabledSensorTable, sensor)
                        del self.disabledSensors[sensor]
                    #save list
        except Exception as ex:
            error('EnableSensor Failed with exception: '  + str(ex))
            return False
        return True
Example #2
0
 def EnableSensor(self, sensor, enable):
     #sensor is the hash composed from name and device class/type
     info('Enable sensor: ' + str(sensor) + ' ' + str(enable))
     try:
         if sensor is None:
             return False
         if enable is None:
             return False
         with self.sensorMutex:
             if enable == 0:
                 #add item to the list
                 if sensor not in self.disabledSensors:
                     rowId = DbManager.Insert(self.disabledSensorTable,
                                              sensor)
                     self.disabledSensors[sensor] = 1
             else:
                 #remove item from the list
                 if sensor in self.disabledSensors:
                     DbManager.Delete(self.disabledSensorTable, sensor)
                     del self.disabledSensors[sensor]
                 #save list
     except Exception as ex:
         error('EnableSensor Failed with exception: ' + str(ex))
         return False
     self.AddRefresh()
     return True
Example #3
0
 def __init__(self):
     self.sensorMutex = RLock()
     self.systemMutex = RLock()
     self.continueMonitoring = False
     self.onDataChanged = None
     self.onSystemInfo = None
     self.currentBusInfo = self.previousBusInfo = None
     self.currentSensorsInfo = self.previousSensorsInfo = None
     self.currentSystemInfo = self.previousSystemInfo = None
     self.cpuLoadValues = {}
     self.disabledSensors = {}
     self.sensorsRefreshCount = 0
     self.retrievingSystemInfo = False
     self.disabledSensorTable = "disabled_sensors"
     self.systemInfoRefreshList = []
     checkAllBus()
     self.gpio = GPIO()
     manager.addDeviceInstance("GPIO", "GPIO", "GPIO", self.gpio, [],
                               "system")
     manager.loadJsonDevices("rest")
     results = DbManager.Select(self.disabledSensorTable)
     if results:
         for row in results:
             self.disabledSensors[row[0]] = 1
     self.StartMonitoring()
Example #4
0
 def __init__(self):
     """Initialize the bus and sensor info and start monitoring sensor states"""
     self.sensorMutex = RLock()
     self.realTimeMutex = RLock()
     self.exiting = Event()
     self.onDataChanged = None
     self.systemData = []
     self.currentSystemState = []
     self.currentRealTimeData = {}                                
     self.queuedRealTimeData = {}
     self.disabledSensors = {}
     self.disabledSensorTable = "disabled_sensors"
     checkAllBus()
     self.gpio = GPIO()
     self.downloadSpeed = DownloadSpeed(Config(APP_SETTINGS))
     self.downloadSpeed.getDownloadSpeed()
     manager.addDeviceInstance("GPIO", "GPIO", "GPIO", self.gpio, [], "system")
     manager.loadJsonDevices("rest")
     results = DbManager.Select(self.disabledSensorTable)
     if results:
         for row in results:
             self.disabledSensors[row[0]] = 1
     self.realTimeMonitorRunning = False
     self.pluginManager = PluginManager(self.OnPluginChange)
     self.pluginManager.load_plugins()
     self.InitCallbacks()
     self.StartMonitoring()
Example #5
0
 def RemoveDbItem(self, id):
     bVal = True
     try:
         with self.mutex:
             DbManager.Delete(self.tablename, id)
     except:
         bVal = False
     return bVal
Example #6
0
 def RemoveAllDbItems(self):
     bVal = True
     try:
         with self.mutex:
             DbManager.DeleteAll(self.tablename)
     except:
         bVal = False
     return bVal
Example #7
0
    def __init__(self, client):
        """Initialize the bus and sensor info and start monitoring sensor states"""
        self.cloudClient = client
        self.sensorMutex = RLock()
        self.realTimeMutex = RLock()
        self.exiting = Event()
        self.onDataChanged = None
        self.systemData = []
        self.currentSystemState = []
        self.currentRealTimeData = {}
        self.queuedRealTimeData = {}
        self.disabledSensors = {}
        self.disabledSensorTable = "disabled_sensors"
        checkAllBus()
        self.gpio = GPIO()
        # self.downloadSpeed = DownloadSpeed(Config(APP_SETTINGS))
        # self.downloadSpeed.getDownloadSpeed()
        manager.addDeviceInstance("GPIO", "GPIO", "GPIO", self.gpio, [],
                                  "system")

        manager.loadJsonDevices("rest")

        if not DYNAMIC_DEVICES:
            warn("loadJsonDevices is None")
            for sensor in sensors.values():
                # info('--------{} {} {}'.format(sensor['name'], sensor['description'], sensor['device']))
                self.AddSensor(sensor['name'], sensor['description'],
                               sensor['device'], sensor['args'])

        #
        # info(DYNAMIC_DEVICES)
        self.config = Config(APP_SETTINGS)
        self.clientId = self.config.get('Agent', 'ClientID', None)
        self.mqtt_dis_prefix = self.config.get('Agent', 'MQTT_DIS_PREFIX',
                                               "homeassistant")
        self.serial = self.cloudClient.hardware.Serial

        for name, device in DYNAMIC_DEVICES.items():

            for type in device['type']:
                if type in ['DAC', 'ADC']:
                    continue
                topic, message = self.AddMQTTSensorDevice(name, type, device)

                if self.cloudClient:
                    info("{} {}".format(topic, message))
                    self.cloudClient.EnqueuePacket(message, topic)
                # info(mqttsensor)

        results = DbManager.Select(self.disabledSensorTable)
        if results:
            for row in results:
                self.disabledSensors[row[0]] = 1
        self.realTimeMonitorRunning = False
        self.pluginManager = PluginManager(self.OnPluginChange)
        self.pluginManager.load_plugins()
        self.InitCallbacks()
        self.StartMonitoring()
Example #8
0
 def LoadData(self):
     with self.mutex:
         results = DbManager.Select(self.tablename)
         if results:
             for row in results:
                 #info('Row: ' + str(row))
                 #for each item already present in db add call AddScheduledItem with insert false
                 self.AddScheduledItem(loads(row[1]), False)
     return True
Example #9
0
 def UpdateDbItem(self, jsonData, id):
     debug('')
     bVal = True
     try:
         setClause = 'data = ?'
         whereClause = 'id = ?'
         with self.mutex:
             DbManager.Update(self.tablename, setClause, jsonData,
                              whereClause, id)
     except:
         bVal = False
     return bVal
Example #10
0
 def __init__(self):
     """Initialize the bus and sensor info and start monitoring sensor states"""
     self.sensorMutex = RLock()
     self.exiting = Event()
     self.onDataChanged = None
     self.onSystemInfo = None
     self.systemData = []
     self.currentSystemState = []
     self.disabledSensors = {}
     self.disabledSensorTable = "disabled_sensors"
     checkAllBus()
     self.gpio = GPIO()
     manager.addDeviceInstance("GPIO", "GPIO", "GPIO", self.gpio, [], "system")
     manager.loadJsonDevices("rest")
     results = DbManager.Select(self.disabledSensorTable)
     if results:
         for row in results:
             self.disabledSensors[row[0]] = 1
     self.StartMonitoring()
Example #11
0
 def test_delayed_load(self):
     self.test_engine.stop()
     del self.test_engine
     del self.test_client
     now = datetime.datetime.utcnow()
     if (now.second > 35):
         print('Sleep until the minute rolls over')
         time.sleep(60 - now.second)
     now = datetime.datetime.strftime(datetime.datetime.utcnow(),
                                      '%Y-%m-%dT%H:%M:%S.%fZ')
     self.schedule_events = [{
         'id': 'delay_1',
         'title': 'date_job',
         'actions': ['date_job_action'],
         'config': {
             'type': 'date',
             'start_date': now
         }
     }, {
         'id': 'delay_2',
         'title': 'daily_job',
         'actions': ['daily_job_action'],
         'config': {
             'type': 'interval',
             'unit': 'day',
             'interval': 1,
             'start_date': now
         }
     }, {
         'id': 'delay_3',
         'title': 'weekly_job',
         'actions': ['weekly_job_action'],
         'config': {
             'type': 'interval',
             'unit': 'week',
             'interval': 1,
             'start_date': now
         }
     }, {
         'id': 'delay_4',
         'title': 'monthly_job',
         'actions': ['monthly_job_action'],
         'config': {
             'type': 'interval',
             'unit': 'month',
             'interval': 1,
             'start_date': now
         }
     }, {
         'id': 'delay_5',
         'title': 'yearly_job',
         'actions': ['yearly_job_action'],
         'config': {
             'type': 'interval',
             'unit': 'year',
             'interval': 1,
             'start_date': now
         }
     }]
     for event in self.schedule_events:
         event_json = json.dumps(event)
         try:
             DbManager.Insert('scheduled_events', event['id'], event_json)
         except sqlite3.IntegrityError as e:
             DbManager.Update('scheduled_events', 'event = ?', event_json,
                              'id = ?', event['id'])
     print('Pause before loading scheduler')
     time.sleep(20)
     print('Starting scheduler, time is {}'.format(
         datetime.datetime.utcnow()))
     self.test_client = TestClient()
     self.test_engine = SchedulerEngine(self.test_client, 'test')
     self.check_schedules_run(self.schedule_events)
Example #12
0
 def AddDbItem(self, id, jsonData):
     debug('')
     bVal = False
     with self.mutex:
         bVal = DbManager.Insert(self.tablename, id, jsonData)
     return bVal