Пример #1
0
    def init(self, config=None, **kwargs):
        try:
            cache = kwargs.get('cache', self.cache)
            _config = self.get_default_config(self.__class__, Device, cache)
            if config:
                Helper.update_dict(_config, config)
            self.resource_layer.init_from_config(_config)
            if not self.get_param('/oic/d', 'piid', None):
                self.set_param('/oic/d', 'piid', str(uuid4()), save_config=kwargs.get('save_config', True))

            di = self.get_device_id()
            if not self.get_device_id():
                di = kwargs.get('di')
            self.set_device_id(di)
            self.change_provisioning_state()
            self.log = logging.getLogger('{0}:{1}'.format(self.__class__.__name__, self.get_device_id()[-5:]))
            self.log.setLevel(getattr(logging, self.get_param('/oic/con', 'logLevel', 'error').upper()))
            return self
        except Exception as e:
            raise ExtException(
                message='Bad driver config',
                detail=self.__class__.__name__,
                action='OcfDevice.init_from_config',
                dump=dict(
                    config=config,
                    kwargs=kwargs
                )
            ) from e
Пример #2
0
 def load_from_rt(self, rt):
     schema = {}
     for name in rt:
         uri = '{0}.json'.format(name)
         _schema = self.load_from_uri(uri)
         Helper.update_dict(schema, _schema)
     return schema
Пример #3
0
    def update_param(self, resource, name, new_value, **kwargs):
        old_value = self.get_param(resource, name)
        difference, changes = Helper.compare(old_value, new_value)
        if difference:
            self._resource_changed[resource] = True
            if isinstance(old_value, dict):
                Helper.update_dict(old_value, changes)
            elif isinstance(old_value, (str, int, float, bool)):
                self.data[resource][name] = changes
            elif isinstance(old_value, list):
                self.log.warning("NOT SUPPORTED OPERATIONS!!!")
                self.data[resource][name] = changes

            if kwargs.get('save_config', False):
                self.save_config()
        return changes
Пример #4
0
 def get_obj_class(obj_name, **kwargs):
     suffix = kwargs.get('suffix')
     class_name = f'{obj_name}{suffix}' if suffix else obj_name
     full_path = f'BubotObj.{obj_name}.{class_name}.{class_name}'
     try:
         return Helper.get_class(full_path)
     except ExtException as err:
         raise HandlerNotFoundError(detail=f'object {obj_name}', parent=err)
Пример #5
0
 def __init__(self, request):
     web.View.__init__(self, request)
     self.obj_type = self.request.match_info.get('objType')
     self.obj_name = self.request.match_info.get('objName')
     self.report_name = self.request.match_info.get('reportName')
     self.report_section = self.request.match_info.get('reportSection')
     try:
         self.handler = Helper.get_obj_class(
             f'jay.{self.obj_type}.{self.obj_name}', 'reports',
             self.report_name)()
     except Exception as err:
         raise err
Пример #6
0
 def test_1(self):
     a = {'/oic/con': {
         'rt': ['oic.wk.con', 'bubot.con', 'bubot.VirtualServer.con'], 'if': ['oic.if.baseline'],
         'p': {'bm': 3}, 'logLevel': 'info', 'udpCoapPort': 0, 'udpCoapIPv4': True,
         'udpCoapIPv6': False, 'udpCoapIPv4Ssl': False, 'udpCoapIPv6Ssl': False, 'listening': [],
         'observed': [], 'running_devices': [], 'port': 80}}
     b = {'/oic/d': {'di': '7f9a4170-8c4e-4ca4-939a-70d91a1393b1'}, '/oic/con': {'udpCoapPort': 64682,
                                                                                 'running_devices': [{
                                                                                     'di': '6e356439-104d-4f79-8b78-aed3666463d9',
                                                                                     'dmno': 'SerialServerHF511',
                                                                                     'n': 'Serial server HF511A'}]}}
     res = Helper.update_dict(a, b)
     pass
Пример #7
0
    def build_i18n(self, drivers):
        locales = {'en': {}, 'ru': {}, 'cn': {}}
        self.log.info('begin')
        for elem in drivers:
            _path = os.path.normpath(f'{drivers[elem]["path"]}/i18n')
            if not os.path.isdir(_path):
                continue
            for locale in locales:
                locale_path = os.path.normpath(
                    f'{drivers[elem]["path"]}/i18n/{locale}.json')
                if not os.path.isfile(locale_path):
                    continue
                with open(locale_path, "r", encoding='utf-8') as file:
                    try:
                        _data = json.load(file)
                        Helper.update_dict(locales[locale], _data)
                    except Exception as err:
                        self.log.error(
                            f'Build locale {locale} for driver {elem}: {str(err)}'
                        )

        i18n_dir = os.path.normpath(f'{self.path}/i18n')
        try:
            os.mkdir(i18n_dir)
        except FileExistsError:
            pass
        except Exception as err:
            raise ResourceNotAvailable(detail=f'{err} - {i18n_dir}',
                                       parent=err)
        for locale in locales:
            build_path = os.path.normpath(f'{i18n_dir}/{locale}.json')
            with open(build_path, "w", encoding='utf-8') as file:
                try:
                    json.dump(locales[locale], file, ensure_ascii=False)
                except Exception as err:
                    self.log.error(f'Build locale {locale}: {str(err)}')

        self.log.info('complete')
Пример #8
0
    def save_config(self):
        def_data = self.get_default_config(self.__class__, Device, self.cache)
        data = Helper.compare(def_data, self.data)
        try:
            data[1].pop('/oic/mnt')
        except KeyError:
            pass

        try:
            with open(self.get_config_path(), 'w', encoding='utf-8') as file:
                json.dump(data[1], file, ensure_ascii=False, indent=2)
        except FileNotFoundError:
            return {}
        return data
Пример #9
0
    def set_param(self, resource, name, new_value, **kwargs):
        try:
            old_value = self.get_param(resource, name, None)
            difference, changes = Helper.compare(old_value, new_value)
            if difference:
                self._resource_changed[resource] = True
                self.data[resource][name] = new_value

                if kwargs.get('save_config', False):
                    self.save_config()
        except Exception as e:
            raise ExtException(detail=str(e),
                               dump=dict(resource=resource,
                                         name=name,
                                         value=new_value))
Пример #10
0
 def load_elem_ref(self, data, value, name):
     res = self.load_from_uri(value)
     Helper.update_dict(data, res)
Пример #11
0
 def test_loads_exception(self):
     res = Helper.loads_exception(
         '{"__module__": "Bubot.Helpers.ExtException", "__name__":"ExtTimeoutError", "message":"test"}')
     self.assertIsInstance(res, ExtException)
     pass
Пример #12
0
 def test_update_string_array(self):
     a = {'t': ['a1', 'a2', 'a3']}
     b = {'t': ['a1', 'a4', 'a3']}
     res = Helper.update_dict(a, b)
     self.assertEqual(len(res['t']), 4)
     pass
Пример #13
0
 def test_update_object_array(self):
     a = {'t': [{'id': 'a1', 'name': 'тест'}, {'id': 'a2', 'name': 'тест'}]}
     b = {'t': [{'id': 'a3', 'name': 'тест'}, {'id': 'a2', 'name': 'тест'}]}
     res = Helper.update_dict(a, b)
     self.assertEqual(len(res['t']), 3)
     pass
Пример #14
0
 def get_default_config(self, current_class, root_class, cache):
     data = Helper.get_default_config(current_class, root_class, cache)
     data['/oic/d']['dmno'] = current_class.__name__
     data['/oic/d']['sv'] = self.version
     data['/oic/p']['mnpv'] = current_class.platform_version
     return data
Пример #15
0
 def init_by_data(self, data):
     self.init()
     if data:
         Helper.update_dict(self.data, data)
     if '_id' not in data:
         self.data['_id'] = str(uuid4())