Exemplo n.º 1
0
def str_to_foc(sfoc):
    """Take a string of 'feed' or 'control' and return the QAPI Resource Const.R_FEED or R_CONTROL
    """
    try:
        return __FOC_STR_MAPPING[sfoc]
    except KeyError as ex:
        raise_from(ValueError('sfoc'), ex)
Exemplo n.º 2
0
def foc_to_str(foc):
    """Take the QAPI Resource code and return string of 'feed' or 'control'
    """
    try:
        return __FOC_CODE_MAPPING[foc]
    except KeyError as ex:
        raise_from(ValueError('foc'), ex)
Exemplo n.º 3
0
def foc_to_str(foc):
    """Take the QAPI Resource code and return string of 'feed' or 'control'
    """
    try:
        return __FOC_CODE_MAPPING[foc]
    except KeyError as ex:
        raise_from(ValueError('foc'), ex)
Exemplo n.º 4
0
def str_to_foc(sfoc):
    """Take a string of 'feed' or 'control' and return the QAPI Resource Const.R_FEED or R_CONTROL
    """
    try:
        return __FOC_STR_MAPPING[sfoc]
    except KeyError as ex:
        raise_from(ValueError('sfoc'), ex)
Exemplo n.º 5
0
 def __get_sub(self, foc, gpid):
     # global
     if isinstance(gpid, string_types):
         gpid = uuid_to_hex(gpid)
     # not local
     elif not (isinstance(gpid, Sequence) and len(gpid) == 2):
         raise ValueError('gpid must be string or two-element tuple')
     try:
         sub = self.__new_subs.pop((foc, gpid))
     except KeyError as ex:
         raise_from(KeyError('Remote%s subscription %s not know as new' % (foc_to_str(foc).capitalize(), gpid)), ex)
     if sub is None:
         raise ValueError('Either subscription not complete yet or point %s is of opposite type. (In which case'
                          ' call %s instead' % (gpid, 'attach()' if foc == R_FEED else 'follow()'))
     return sub
Exemplo n.º 6
0
    def get_thing(self, lid):
        """Get the details of a newly created Thing. This only applies to asynchronous creation of Things and the
        new Thing instance can only be retrieved once.

        Returns a [Thing](Thing.m.html#IoticAgent.IOT.Thing.Thing) object,
        which corresponds to the Thing with the given local id (nickname)

        Raises `KeyError` if the Thing has not been newly created (or has already been retrieved by a previous call)

        `lid` (required) (string) local identifier of your Thing.
        """
        with self.__new_things:
            try:
                return self.__new_things.pop(lid)
            except KeyError as ex:
                raise_from(KeyError('Thing %s not know as new' % lid), ex)
Exemplo n.º 7
0
    def get_control(self, pid):
        """Get the details of a newly created control. This only applies to asynchronous creation of feeds and the new
        control instance can only be retrieved once.

        `NOTE` - Destructive Read. Once you've called get_control once, any further calls will raise a `KeyError`

        Returns a [Point](Point.m.html#IoticAgent.IOT.Point.Point) object,
        which corresponds to the cached entry for this local point id

        `pid` (required) (string) local identifier of your control.

        Raises `KeyError` if the control has not been newly created (or has already been retrieved by a previous call)
        """
        with self.__new_controls:
            try:
                return self.__new_controls.pop(pid)
            except KeyError as ex:
                raise_from(KeyError('Control %s not know as new' % pid), ex)
Exemplo n.º 8
0
 def __sub(self, foc, gpid, callback=None):
     evt = self.__sub_async(foc, gpid, callback=callback)
     self._client._wait_and_except_if_failed(evt)
     try:
         return self.__get_sub(foc, gpid)
     except KeyError as ex:
         raise raise_from(
             IOTClientError(
                 'Subscription for %s (from %s) not in cache (post-create)'
                 % gpid, self.__lid), ex)
Exemplo n.º 9
0
 def __sub(self, foc, gpid, callback=None):
     logger.info("__sub(foc=%s, gpid=\"%s\", callback=%s) [lid=%s]", foc_to_str(foc), gpid, callback, self.__lid)
     evt = self.__sub_make_request(foc, gpid, callback)
     evt.wait(self.__client.sync_timeout)
     self.__client._except_if_failed(evt)
     try:
         return self.__get_sub(foc, gpid)
     except KeyError as ex:
         raise raise_from(IOTClientError('Subscription for %s (from %s) not in cache (post-create)' %
                                         gpid, self.__lid),
                          ex)
Exemplo n.º 10
0
 def __get_sub(self, foc, gpid):
     # global
     if isinstance(gpid, string_types):
         gpid = uuid_to_hex(gpid)
     # not local
     elif not (isinstance(gpid, Sequence) and len(gpid) == 2):
         raise ValueError('gpid must be string or two-element tuple')
     try:
         # Not using ThreadSafeDict lock since pop() is atomic operation
         sub = self.__new_subs.pop((foc, gpid))
     except KeyError as ex:
         raise_from(
             KeyError('Remote%s subscription %s not know as new' %
                      (foc_to_str(foc).capitalize(), gpid)), ex)
     if sub is None:
         raise ValueError(
             'Either subscription not complete yet or point %s is of opposite type. (In which case'
             ' call %s instead' %
             (gpid, 'attach()' if foc == R_FEED else 'follow()'))
     return sub
Exemplo n.º 11
0
 def __create_point(self, foc, pid, control_cb=None):
     evt = self.__client._request_point_create(foc, self.__lid, pid, control_cb=control_cb)
     evt.wait(self.__client.sync_timeout)
     self.__client._except_if_failed(evt)
     store = self.__new_feeds if foc == R_FEED else self.__new_controls
     try:
         with store:
             return store.pop(pid)
     except KeyError as ex:
         raise raise_from(IOTClientError('%s %s (from %s) not in cache (post-create)' %
                                         (foc_to_str(foc), pid, self.__lid)),
                          ex)
Exemplo n.º 12
0
    def get_feed(self, pid):
        """
        Get the details of a newly created feed. This only applies to asynchronous creation of feeds and the new feed
        instance can only be retrieved once.

        Note:
            Destructive Read. Once you've called get_feed once, any further calls will raise a `KeyError`

        Returns:
            A :doc:`IoticAgent.IOT.Point` feed object, which corresponds to the cached entry for this local feed id.

        Args:
            pid (string): Point id - local identifier of your feed.

        Raises:
            KeyError: Feed has not been newly created (or has already been retrieved by a previous call)
        """
        with self.__new_feeds:
            try:
                return self.__new_feeds.pop(pid)
            except KeyError as ex:
                raise_from(KeyError('Feed %s not know as new' % pid), ex)
Exemplo n.º 13
0
 def __create_point(self, foc, pid, control_cb=None, save_recent=0):
     evt = self.__create_point_async(foc,
                                     pid,
                                     control_cb=control_cb,
                                     save_recent=save_recent)
     self._client._wait_and_except_if_failed(evt)
     store = self.__new_feeds if foc == R_FEED else self.__new_controls
     try:
         with store:
             return store.pop(pid)
     except KeyError as ex:
         raise raise_from(
             IOTClientError('%s %s (from %s) not in cache (post-create)' %
                            (foc_to_str(foc), pid, self.__lid)), ex)
Exemplo n.º 14
0
    def create_thing(self, lid):
        """Create a new Thing with a local id (lid).

        Returns a [Thing](Thing.m.html#IoticAgent.IOT.Thing.Thing)  object if successful
        or if the Thing already exists

        Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
        containing the error if the infrastructure detects a problem

        Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
        if there is a communications problem between you and the infrastructure

        `lid` (required) (string) local identifier of your Thing.  The local id is your name or nickname for the thing.
        It's "local" in that it's only available to you on this container, not searchable and not visible to others.
        """
        logger.info("create_thing(lid=\"%s\")", lid)
        evt = self._request_entity_create(lid)
        evt.wait(self.__sync_timeout)
        self._except_if_failed(evt)
        try:
            with self.__new_things:
                return self.__new_things.pop(lid)
        except KeyError as ex:
            raise raise_from(IOTClientError('Thing %s not in cache (post-create)' % lid), ex)
Exemplo n.º 15
0
    def __init__(self, config=None, db=None):
        """
        Creates an IOT.Client instance which provides access to Iotic Space

        `config` (optional): The name of the config file containing the connection parameters.
        Defaults to the name of the script +".ini", e.g. `config="my_script.ini"`. Alternatively
        an existing [Config](Config.m.html#IoticAgent.IOT.Config.Config) object can be specified.

        `db` (optional): The name of the database file to be used for storing key-value pairs by the agent.
        Defaults to the name of the script +".db", e.g. `db="my_script.db"`
        """
        self.__core_version_check()
        logger.info('IOT version: %s', __version__)
        #
        if isinstance(config, string_types) or config is None:
            self.__config = Config(config)
        elif isinstance(config, Config):
            self.__config = config
        else:
            raise ValueError('config should be string or Config instance')
        #
        if any(self.__config.get('agent', item) is None for item in ('host', 'epid', 'passwd', 'token')):
            raise ValueError('Minimum configuration for IoticAgent is host, epid, passwd and token\n'
                             'Create file "%s" with contents\n[agent]\nhost = w\nepid = x\npasswd = y\ntoken = z'
                             % self.__config._file_loc())
        self.__sync_timeout = validate_nonnegative_int(self.__config.get('iot', 'sync_request_timeout'),
                                                       'iot.sync_request_timeout', allow_zero=False)
        self.__config.setup_logging()
        #
        try:
            self.__client = Core_Client(host=self.__config.get('agent', 'host'),
                                        vhost=self.__config.get('agent', 'vhost'),
                                        epId=self.__config.get('agent', 'epid'),
                                        lang=self.__config.get('agent', 'lang'),
                                        passwd=self.__config.get('agent', 'passwd'),
                                        token=self.__config.get('agent', 'token'),
                                        prefix=self.__config.get('agent', 'prefix'),
                                        sslca=self.__config.get('agent', 'sslca'),
                                        network_retry_timeout=self.__config.get('core', 'network_retry_timeout'),
                                        socket_timeout=self.__config.get('core', 'socket_timeout'),
                                        auto_encode_decode=bool_from(self.__config.get('core', 'auto_encode_decode')),
                                        send_queue_size=self.__config.get('core', 'queue_size'),
                                        throttle_conf=self.__config.get('core', 'throttle'))
        except ValueError as ex:
            raise_from(ValueError('Configuration error'), ex)

        #
        # Callbacks for updating own resource cache (used internally only)
        self.__client.register_callback_created(self.__cb_created)
        self.__client.register_callback_duplicate(self.__cb_duplicated)
        self.__client.register_callback_reassigned(self.__cb_reassigned)
        self.__client.register_callback_deleted(self.__cb_deleted)
        #
        # Setup catchall for unsolicited feeddata and controlreq and write data to the key/value DB
        self.__db = None
        if bool_from(self.__config.get('iot', 'db_last_value')):
            self.__db = DB(fn=db)
            self.__client.register_callback_feeddata(self.__cb_catchall_feeddata)
            self.__client.register_callback_controlreq(self.__cb_catchall_controlreq)
        #
        # Keeps track of newly created things (the requests for which originated from this agent)
        self.__new_things = ThreadSafeDict()
        # Allows client to forward e.g. Point creation callbacks to the relevant Thing instance. This contains the most
        # recent instance of any single Thing (since creation requests can be performed more than once).
        self.__private_things = ThreadSafeDict()