def _evaluate(self, unknown_devices, init):
     missing_devices, new_devices, changed_devices = self._diff(__class__._known_devices, unknown_devices)
     if missing_devices:
         for missing_device_id in missing_devices:
             logger.info("can't find '{}' with id '{}'".format(__class__._known_devices[missing_device_id].get('name'), missing_device_id))
             del __class__.bridge_map[missing_device_id]
             if init:
                 DevicePool.remove(missing_device_id)
             else:
                 Client.disconnect(missing_device_id)
     if new_devices:
         for new_device_id in new_devices:
             name = unknown_devices[new_device_id].get('name')
             logger.info("found '{}' with id '{}'".format(name, new_device_id))
             __class__.bridge_map[new_device_id] = (unknown_devices[new_device_id].get('LIGHT_KEY'), Converter(get_light_gamut(unknown_devices[new_device_id].get('modelid'))))
             device = Device(new_device_id, SEPL_DEVICE_TYPE, name)
             device.addTag('type', unknown_devices[new_device_id].get('type'))
             device.addTag('manufacturer', unknown_devices[new_device_id].get('manufacturername'))
             if init:
                 DevicePool.add(device)
             else:
                 Client.add(device)
     if changed_devices:
         for changed_device_id in changed_devices:
             device = DevicePool.get(changed_device_id)
             name = unknown_devices[changed_device_id].get('name')
             if not name == device.name:
                 device.name = name
                 if init:
                     DevicePool.update(device)
                 else:
                     Client.update(device)
                 logger.info("name of '{}' changed to {}".format(changed_device_id, name))
     __class__._known_devices = unknown_devices
Exemplo n.º 2
0
 def __init__(self, serial_con, dip_id, greeting, callbk):
     super().__init__()
     self._serial_con = serial_con
     self._id = dip_id
     self._extended_id = "{}-{}".format(self._id, ID_PREFIX)
     self._greeting = greeting
     self._callbk = callbk
     self._commands = Queue()
     self._serial_logger = serial_logger.getChild(self._id)
     self.log_file = os.path.join(
         os.path.dirname(__file__),
         '{}/{}.log'.format(devices_path, self._id))
     if not self._serial_logger.hasHandlers():
         log_handler = logging.FileHandler(self.log_file)
         log_handler.setFormatter(
             logging.Formatter(fmt='%(asctime)s: %(message)s',
                               datefmt='%m.%d.%Y %I:%M:%S %p'))
         self._serial_logger.addHandler(log_handler)
     if self._loadDeviceInfo():
         self._device = Device(self._extended_id,
                               "iot#fd0e1327-d713-41da-adfb-e3853a71db3b",
                               self._meter_name)
         self._device.addTag("type1", "Ferraris Meter")
         self._device.addTag("type2", "Optical Sensor")
         self.start()
     else:
         self._callbk(self._serial_con.port)
Exemplo n.º 3
0
 def devices() -> dict:
     query = 'SELECT * FROM {table}' \
             'WHERE status = 1'.format(
         table=__class__._devices_table
     )
     result = DB._executeQuery(query)
     devices = dict()
     if result:
         for r in result:
             device = Device(str([0]), r[2], r[1])
             devices[device.id] = device
     return devices
Exemplo n.º 4
0
 def get(id):
     query = """
             SELECT * FROM endpoints
             WHERE id = {id}
             """.format(id=id)
     result = DB._executeQuery(query)
     if result:
         result = result[0]
         new_device = Device(str(result[0]), result[2], result[1])
         return new_device
     else:
         return None
 def devices(self) -> dict:
     query = 'SELECT * FROM {table}'.format(table=__class__._devices_table)
     result = self._executeQuery(query)
     devices = dict()
     for item in result:
         device = Device(item[0], item[1], item[2])
         try:
             for key_value in item[3].split(';'):
                 device.addTag(*key_value.split(':', 1))
         except Exception as ex:
             logger.error(ex)
         devices[device.id] = device
     return devices
Exemplo n.º 6
0
 def _evaluate(self, unknown_devices):
     missing_devices, new_devices, changed_devices = self._diff(__class__._known_devices, unknown_devices)
     if missing_devices:
         for missing_device_id in missing_devices:
             logger.info("can't find '{}' with id '{}'".format(__class__._known_devices[missing_device_id].get('label'), missing_device_id))
             try:
                 Client.delete(missing_device_id)
             except AttributeError:
                 DevicePool.remove(missing_device_id)
     if new_devices:
         for new_device_id in new_devices:
             name = unknown_devices[new_device_id].get('label')
             logger.info("found '{}' with id '{}'".format(name, new_device_id))
             device = Device(new_device_id, SEPL_DEVICE_TYPE, name)
             product = unknown_devices[new_device_id].get('product')
             device.addTag('type', 'Extended color light')
             device.addTag('product', product.get('name'))
             device.addTag('manufacturer', product.get('company'))
             try:
                 Client.add(device)
             except AttributeError:
                 DevicePool.add(device)
     if changed_devices:
         for changed_device_id in changed_devices:
             seconds_since_seen = unknown_devices[changed_device_id].get('seconds_since_seen')
             if seconds_since_seen >= 60:
                 try:
                     Client.disconnect(changed_device_id)
                 except AttributeError:
                     DevicePool.remove(changed_device_id)
                 del unknown_devices[changed_device_id]
             else:
                 device = DevicePool.get(changed_device_id)
                 name = unknown_devices[changed_device_id].get('label')
                 if not name == device.name:
                     device.name = name
                     try:
                         Client.update(device)
                     except AttributeError:
                         DevicePool.update(device)
                     logger.info("name of '{}' changed to {}".format(changed_device_id, name))
     __class__._known_devices = unknown_devices
 def get(self, id_str) -> Device:
     if type(id_str) is not str:
         raise TypeError("id must be a string but got '{}'".format(
             type(id_str)))
     query = 'SELECT {type}, {name}, {tags} FROM {table} WHERE {id}="{id_v}"'.format(
         table=__class__._devices_table,
         type=__class__._type_field[0],
         name=__class__._name_field[0],
         tags=__class__._tags_field[0],
         id=__class__._id_field[0],
         id_v=id_str)
     result = self._executeQuery(query)
     if result:
         device = Device(id_str, result[0][0], result[0][1])
         try:
             for key_value in result[0][2].split(';'):
                 device.addTag(*key_value.split(':', 1))
         except Exception as ex:
             logger.error(ex)
         return device
tests = scenario[6]

logger.info('###### initiation phase ######')

id_1 = 'asdsdfsf24t'
id_2 = '3g46h4h6h436h'
id_3 = '46j5j67j6rt'
id_4 = '3h6j6i8i7rer5'

device_manager = DevicePool

if 0 in tests:
    logger.info('------ populate device manager ------')
    device_manager.add(
        Device(id_1, 'iot#d66ec9bc-e37f-4f35-a788-027301aad6c2',
               'Dummy Device 1'))
    device_2 = Device(id_2, 'iot#d66ec9bc-e37f-4f35-a788-027301aad6c2',
                      'Dummy Device 2')
    device_2.addTag('type', 'Dummy')
    device_manager.add(device_2)
    device_manager.add(
        Device(id_3, 'iot#d66ec9bc-e37f-4f35-a788-027301aad6c2',
               'Dummy Device 3'))

if __name__ == '__main__':
    connector_client = Client(device_manager)

    logger.info('###### runtime phase ######')

    if 1 in tests:
        time.sleep(0.5)
try:
    from connector_client.modules.http_lib import Methods as http
    from connector_client.modules.device_pool import DevicePool
    from connector_client.client import Client
    from connector_client.device import Device
    from configuration import SM_ID, SM_NAME, SM_MANUFACTURER, SM_TYPE, SEPL_DEVICE_TYPE, SEPL_SERVICE
    from smart_meter_serial import SmartMeterSerial
    from logger import root_logger
except ImportError as ex:
    exit("{} - {}".format(__name__, ex.msg))
import datetime, json

logger = root_logger.getChild(__name__)

smart_meter = Device(SM_ID, SEPL_DEVICE_TYPE, SM_NAME)
if SM_TYPE:
    smart_meter.addTag('type', SM_TYPE)
if SM_MANUFACTURER:
    smart_meter.addTag('manufacturer', SM_MANUFACTURER)
DevicePool.add(smart_meter)

sm_serial = SmartMeterSerial()


def getReading(source):
    payload = dict()
    while True:
        readings = source.read()
        if readings:
            payload['value'] = float(readings['1.8.0'][0])