Example #1
0
 def send(self, notification, acl):
     ServiceHub.retrieve(SocketIOSrv).send_notification(
         {
             'uuid': str(notification.uuid),
             'message': notification.msg,
             'severity': notification.severity,
             'time': notification.timestamp.timestamp()
         }, acl)
Example #2
0
 def data_to_ep(self, endpoint, params):
     if 'state' not in params.keys() or params['state'] is None:
         return
     ap = endpoint.alarm_params
     if ap.triggered == params['state']:
         return
     ap.set_state(state=params['state'])
     # TODO Should it be configured outside of the function?
     if bool(params['state']) is True:
         msg = ap.msg_on
         severity = ap.severity
     else:
         msg = ap.msg_off
         severity = AlarmSeverityEnum.Info
     ServiceHub.retrieve(NotificationSrv).new(msg, severity.name, ap.acl)
Example #3
0
 def decode(self):
     decoded = source_decode(self)
     redis = ServiceHub.retrieve(RedisSrv)
     for key in decoded.keys():
         redis.try_update(str(self.uuid), key, decoded[key])
     DeviceSourceMdl.send_to_endpoint(dev_uuid=self.uuid,
                                      key_values=decoded)
Example #4
0
    def get(self, session):
        user = get_jwt_identity()
        user_model = UserMdl.get_user_with_username(username=user,
                                                    session=session)

        return ServiceHub.retrieve(SocketIOSrv).generate_key(
            uuid=user_model.uuid, acl=user_model.acl)
Example #5
0
 def decode(self):
     redis = ServiceHub.retrieve(RedisSrv)
     color = redis.hget(str(self.device.uuid), 'color')
     if color is None:
         return {'red': None, 'green': None, 'blue': None}
     values = convert_from_hex(color)
     return {'red': values[0], 'green': values[1], 'blue': values[2]}
Example #6
0
 def encode(self):
     redis = ServiceHub.retrieve(RedisSrv)
     red = redis.hget(str(self.device.uuid), 'red')
     green = redis.hget(str(self.device.uuid), 'green')
     blue = redis.hget(str(self.device.uuid), 'blue')
     if any(x is None for x in [red, green, blue]):
         return {'color': None}
     return {'color': convert_to_hex(red, green, blue)}
Example #7
0
    def encode(self):
        redis = ServiceHub.retrieve(RedisSrv)

        condition = redis.hget(str(self.device.uuid), 'condition')
        trigger = redis.hget(str(self.device.uuid), 'trigger')
        if trigger is None or condition is None:
            return {'triggered': False}
        return {'triggered': condition, 'trigger': condition}
Example #8
0
 def wrapper(*args, **kwargs):
     if 'session' not in kwargs.keys():
         s = ServiceHub.retrieve(DatabaseSrv).session()
         kwargs['session'] = s
         res = func(*args, **kwargs)
         s.close()
         return res
     else:
         return func(*args, **kwargs)
def delete_endpoints(endpoints, session):
    for num, item in enumerate(endpoints):
        try:
            endpoint = delete_endpoint(item=item, session=session)
        except UnmappedInstanceError as e:
            raise SimpleException('Item #{} not found. Stopping'.format(num))
        driver = ServiceHub.retrieve(DriverSrv).get(endpoint.driver_uuid)
        driver.delete_endpoint(endpoint)
    session.commit()
Example #10
0
    def send_to_endpoint(cls, dev_uuid, key_values, session):
        from py.srv.drivers import DriverSrv
        dss = session \
            .query(cls) \
            .filter(cls.device_uuid == dev_uuid) \
            .filter(cls.device_param.in_(key_values.keys())) \
            .all()

        filtered = {}
        for key, group in groupby(dss, lambda x: x.endpoint_uuid):
            filtered[key] = {}
            for item in group:
                filtered[key][item.endpoint_param] = key_values[
                    item.device_param]

        for key in sorted(filtered.keys(),
                          key=lambda x: min(filtered[key].values())):
            ep = EndpointMdl.get_endpoint_by_uuid(uuid=key, session=session)
            ServiceHub.retrieve(DriverSrv).get(ep.driver.uuid).data_to_ep(
                ep, filtered[key])
Example #11
0
 def decode(self):
     redis = ServiceHub.retrieve(RedisSrv)
     state = redis.hget(str(self.device.uuid), 'state')
     if state not in [0, 1, 2, 3]:
         return {'power': None, 'low': None, 'medium': None, 'high': None}
     return {
         'power': int(state != 0),
         'low': int(state == 1),
         'medium': int(state == 2),
         'high': int(state == 3)
     }
Example #12
0
def set_state(uuid, parameters, acl, session):
    device = DeviceMdl.get_device_with_uuid(uuid=uuid, session=session)
    if device is None:
        raise IncorrectTargetException(uuid, DeviceMdl)
    if device.interface.write_acl > acl:
        raise SimpleException('Not allowed for current user')
    if not all(item in parameters.keys() for item in device.get_key_values()):
        raise SimpleException('Incorrect parameter list')

    redis = ServiceHub.retrieve(RedisSrv)
    if any(redis.try_update(str(uuid), key, parameters[key]) for key in parameters.keys()):
        device.decode()
Example #13
0
    def execute(self, session):
        params = dict([x.as_pair() for x in self.parameters])

        if self.instruction_type == InstructionTypeEnum.SetValue:
            source = DeviceMdl.get_device_with_uuid(uuid=str(params['source']),
                                                    session=session)
            target = DeviceMdl.get_device_with_uuid(uuid=str(params['target']),
                                                    session=session)
            kv = source.get_key_values()
            if params['s_param'] not in kv or params[
                    't_param'] not in target.get_key_values():
                return
            ServiceHub.retrieve(RedisSrv).try_update(str(params['target']),
                                                     params['t_param'],
                                                     kv[params['s_param']])
            #ServiceHub.retrieve(RedisSrv).hset(str(params['target']),
            #                                   params['t_param'],
            #                                   kv[params['s_param']])
            target.decode()
        if self.instruction_type == InstructionTypeEnum.WaitSec:
            seconds = params['seconds']
            time.sleep(seconds)
Example #14
0
def add_endpoints(endpoints, session):
    res = list()
    for num, item in enumerate(endpoints):
        try:
            endpoint = add_endpoint(item=item, session=session)
        except IntegrityError as e:
            raise SimpleException(
                'Duplicate on #{} in sequence. Stopping'.format(num))
        driver = ServiceHub.retrieve(DriverSrv).get(endpoint.driver_uuid)
        driver.add_endpoint(endpoint)
        res.append(endpoint)
    session.commit()
    return res
Example #15
0
    def is_met(self):
        redis = ServiceHub.retrieve(RedisSrv)
        source = redis.hget(str(self.source_dev_uuid), self.source_parameter)
        target = redis.hget(str(self.target_dev_uuid), self.target_parameter)

        if self.condition_type == ConditionTypeEnum.IsEqual:
            return source == target
        if self.condition_type == ConditionTypeEnum.IsLess:
            return source < target
        if self.condition_type == ConditionTypeEnum.IsMore:
            return source > target
        if self.condition_type == ConditionTypeEnum.NotEqual:
            return source != target
 def encode(self):
     redis = ServiceHub.retrieve(RedisSrv)
     target = redis.hget(str(self.device.uuid), 'target')
     value = redis.hget(str(self.device.uuid), 'raw')
     tolerance = redis.hget(str(self.device.uuid), 'tolerance')
     if value is None:
         return {
             'value': None,
             'emergency': False
         }
     return {
         'value': value,
         'emergency': InBorderTargetValueEnt.check_emergency(value, target, tolerance)
     }
Example #17
0
 def send_to_device(cls, ep_uuid, parameters, session):
     dss = session\
         .query(cls)\
         .filter(cls.endpoint_uuid == ep_uuid)\
         .filter(cls.endpoint_param.in_(parameters.keys()))\
         .all()
     redis = ServiceHub.retrieve(RedisSrv)
     devices = list()
     for item in dss:
         if redis.try_update(str(item.device_uuid), item.device_param,
                             parameters[item.endpoint_param]):
             devices.append(item.device_uuid)
     for item in set(devices):
         DeviceMdl.get_device_with_uuid(uuid=item, session=session).encode()
Example #18
0
 def encode(self):
     redis = ServiceHub.retrieve(RedisSrv)
     power = redis.hget(str(self.device.uuid), 'power')
     low = redis.hget(str(self.device.uuid), 'low')
     medium = redis.hget(str(self.device.uuid), 'medium')
     high = redis.hget(str(self.device.uuid), 'high')
     if any(x not in [0, 1] for x in [power, low, medium, high]):
         return {'state': None}
     if [power, low, medium, high] == [0, 0, 0, 0]:
         return {'state': 0}
     if [power, low, medium, high] == [1, 1, 0, 0]:
         return {'state': 1}
     if [power, low, medium, high] == [1, 0, 1, 0]:
         return {'state': 2}
     if [power, low, medium, high] == [1, 0, 0, 1]:
         return {'state': 3}
     return {'state': None}
Example #19
0
def authenticate(sid, data):
    logger.info('Sid {} trying to login...'.format(sid))
    io = ServiceHub.retrieve(SocketIOSrv)
    if 'key' not in data.keys() or data['key'] is None:
        io.sio.emit('auth', {'success': False, 'message': 'No key provided'})
        logger.warning('No key for sid {}'.format(sid))
        return
    for uuid in io.access.keys():
        if io.access[uuid][0] == data['key']:
            io.add_to_room(io.access[uuid][1], sid)
            io.sio.emit('auth', {
                'success': True,
                'message': 'successful authentication'
            })
            logger.info('Successful authentication for sid {}'.format(sid))
            return
    io.sio.emit('auth', {
        'success': False,
        'message': 'Incorrect data provided'
    })
    logger.warning('Incorrect key for sid {}'.format(sid))
Example #20
0
def process_modifications(mods, session):
    eps = dict()
    try:
        eps['added'] = (process_add(mods=mods['added'], session=session))
        eps['removed'] = (process_delete(mods=mods['removed'],
                                         session=session))
        eps['changed'] = (process_edit(mods=mods['changed'], session=session))
    except ApiOperationError as e:
        session.rollback()
        raise e
    for item in eps['added']:
        ServiceHub.retrieve(DriverSrv).get(item.driver_uuid).add_endpoint(item)
    for item in eps['removed']:
        ServiceHub.retrieve(DriverSrv).get(
            item.driver_uuid).delete_endpoint(item)
    for item in eps['changed']:
        ServiceHub.retrieve(DriverSrv).get(
            item.driver_uuid).update_endpoint(item)
    session.commit()
Example #21
0
 def outputs(device):
     redis = ServiceHub.retrieve(RedisSrv)
     params = redis.hgetall(str(device.uuid))
     return params.keys()
Example #22
0
 def encode(self):
     encoded = source_encode(self)
     redis = ServiceHub.retrieve(RedisSrv)
     for key in encoded.keys():
         redis.try_update(str(self.uuid), key, encoded[key])
Example #23
0
def correct_values(mapper, connection, target):
    redis = ServiceHub.retrieve(RedisSrv)
    v = redis.hget(str(target.endpoint_uuid), target.endpoint_param)
    redis.hset(str(target.device_uuid), target.device_param, v)
    target.device.encode()
Example #24
0
 def encode(self):
     redis = ServiceHub.retrieve(RedisSrv)
     params = redis.hgetall(str(self.device.uuid))
     return params
Example #25
0
 def get_key_values(self):
     redis = ServiceHub.retrieve(RedisSrv)
     names = outputs(self)
     return {x: redis.hget(str(self.uuid), x) for x in names}
Example #26
0
 def encode(self):
     redis = ServiceHub.retrieve(RedisSrv)
     v = redis.hget(str(self.device.uuid), 'raw')
     if v is None:
         return {'enabled': None}
     return {'enabled': bool(v)}
Example #27
0
 def data_from_ep(payload, params):
     parameters = params.type.as_dict(payload)
     for item in parameters.items():
         ServiceHub.retrieve(RedisSrv).hset(params.endpoint.uuid, item[0],
                                            item[1])
     DeviceSourceMdl.send_to_device(params.endpoint.uuid, parameters)
Example #28
0
 def decode(self):
     redis = ServiceHub.retrieve(RedisSrv)
     v = redis.hget(str(self.device.uuid), 'enabled')
     if v is None:
         return {'raw': None}
     return {'raw': int(v)}
Example #29
0
def disconnect(sid):
    logger.debug('Disconnecting socketio user with sid {}'.format(sid))
    ServiceHub.retrieve(SocketIOSrv).delete_from_room(sid)
Example #30
0
 def get_all_values(self):
     redis = ServiceHub.retrieve(RedisSrv)
     return redis.hgetall(str(self.uuid))