IoticAgent.IOT.Client module

The Client object used to initiate connection to Iotic Space

class IoticAgent.IOT.Client.Client(config=None)

Bases: object

agent_id

Agent id (aka epId) in use for this client instance

confirm_tell(data, success)

Confirm that you’ve done as you were told. Call this from your control callback to confirm action. Used when you are advertising a control and you want to tell the remote requestor that you have done what they asked you to.

Example

This is a minimal example to show the idea.

Note

No Exception handling and ugly use of globals

client = None

def controlreq_cb(args):
    global client   # the client object you connected with

    # perform your action with the data they sent
    success = do_control_action(args['data'])

    if args['confirm']:  # you've been asked to confirm
        client.confirm_tell(args, success)
    # else, if you do not confirm_tell() this causes a timeout at the requestor's end.

client = IOT.Client(config='test.ini')
thing = client.create_thing('test321')
control = thing.create_control('control', controlreq_cb)
Raises:
  • IOTException – Infrastructure problem detected
  • LinkException – Communication problem between you and the infrastructure
Parameters:
  • data (dictionary) – The “args” dictionary that your callback was called with
  • success (boolean) – Whether or not the action you have been asked to do has been sucessful

More details on the contents of the data dictionary for controls see IoticAgent.IOT.Thing module create_control.

create_thing(lid)

Create a new Thing with a local id (lid).

Returns:

A IoticAgent.IOT.Thing module Thing object if successful or if the Thing already exists

Raises:
  • IOTException – Infrastructure problem detected
  • LinkException – Communications problem between you and the infrastructure
Parameters:

lid (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.

create_thing_async(lid)
default_lang

Language in use when not explicitly specified (in meta related requests). Will be set to container default if was not set in configuration. Before client has started this might be None.

delete_thing(lid)

Delete a Thing

Raises:
  • IOTException – Infrastructure problem detected
  • LinkException – Communications problem between you and the infrastructure

lid (string) local identifier of the Thing you want to delete

delete_thing_async(lid)
describe(guid_or_resource, lang=None, scope=<DescribeScope.AUTO: 'auto'>)

Describe returns the public (or local) description of a Thing or Point

Returns:The description dict (see below for Thing example) if available, otherwise None
{
    "type": "Entity",
    "meta": {
        "long": 0.716356,
        "lat": 52.244384,
        "label": "Weather Station #1",
        "parent": "3bbf307b43b1460289fe707619dece3d",
        "points": [
            {
                "type": "Control",
                "label": "Control 101",
                "guid": "fb1a4a4dbb2642ab9f836892da93c101",
                "storesRecent": false
            },
            {
                "type": "Feed",
                "label": "My weather feed",
                "guid": "fb1a4a4dbb2642ab9f836892da93f101",
                "storesRecent": true
            }
        ],
        "comment": "A lovely weather station...",
        "tags": [
            "blue",
            "garden"
        ]
    }
}
Raises:
  • IOTException – Infrastructure problem detected
  • LinkException – Communications problem between you and the infrastructure
Parameters:
  • guid_or_resource (string or object) – If a string, it should contain the globally unique id of the resource you want to describe in 8-4-4-4-12 (or undashed) format. If an object, it should be an instance of Thing, Point, RemoteFeed or RemoteControl. The system will return you the description of that object.
  • lang (string, optional) – The two-character ISO 639-1 language code for which labels and comments will be returned. This does not affect Values (i.e. when describing a Point, apart from value comments) and tags as these are language neutral).
  • scope (optional) – Whether to perform PUBLIC, LOCAL (container level) or LOCAL_OWN (container level restricted to own things) metadata lookup. Check the IoticAgent.IOT.Client module Client.local_meta flag to determine whether local metadata functionality is available. (Note that AUTO, PUBLIC and LOCAL_OWN scopes are always available.). AUTO mode first attempts to look up private metadata, then public.
get_thing(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 IoticAgent.IOT.Thing module Thing object, which corresponds to the Thing with the given local id (nickname)
Raises:KeyError – The Thing has not been newly created (or has already been retrieved by a previous call)
Parameters:lid (string) – local identifier of your Thing.
is_connected()
Returns:Client’s alive state
list(all_my_agents=False, limit=500, offset=0)

List all the things created by this client on this or all your agents

Returns:

QAPI list function payload

Raises:

LinkException – Communications problem between you and the infrastructure

Parameters:
  • all_my_agents (boolean, optional) – If False limit search to just this agent, if True return list of things belonging to all agents you own.
  • limit (integer, optional) – Return this many Point details
  • offset (integer, optional) – Return Point details starting at this offset
local_meta

Whether container-local metadata functionality (e.g. search) is available in this container. Before calling start() this will always be False.

register_callback_created(func, serialised=True)

Register a callback for resource creation. This will be called when any new resource is created within your agent. If serialised is not set, the callbacks might arrive in a different order to they were requested.

The payload passed to your callback is an OrderedDict with the following keys

r         : R_ENTITY, R_FEED, etc # the type of resource created
lid       : <name>                # the local name of the resource
id        : <GUID>                # the global Id of the resource
epId      : <GUID>                # the global Id of your agent

Note

Resource types are defined in IoticAgent.Core.Const module

Example

def created_callback(args):
    print(args)
...
client.register_callback_created(created_callback)

This would print out something like the following on creation of an R_ENTITY

OrderedDict([(u'lid', u'new_thing1'), (u'r', 1),
             (u'epId', u'ffd47b75ea786f55c76e337cdc47665a'),
             (u'id', u'3f11df0a09588a6a1a9732e3837765f8')]))
register_callback_deleted(func, serialised=True)

Register a callback for resource deletion. This will be called when any resource is deleted within your agent. If serialised is not set, the callbacks might arrive in a different order to they were requested.

The payload passed to your callback is an OrderedDict with the following keys

r         : R_ENTITY, R_FEED, etc # the type of resource deleted
lid       : <name>                # the local name of the resource
id        : <GUID>                # the global Id of the resource

Note

Resource types are defined in IoticAgent.Core.Const module

Example

def deleted_callback(args):
    print(args)
...
client.register_callback_deleted(deleted_callback)

This would print out something like the following on deletion of an R_ENTITY

OrderedDict([(u'lid', u'old_thing1'),
             (u'r', 1),
             (u'id', u'315637813d801ec6f057c67728bf00c2')])
register_callback_duplicate(func, serialised=True)
Register a callback for resource creation but where the resource already exists in Iotic Space. In this case
the existing reference is passed to you. If serialised is not set, the callbacks might arrive in a different order to they were requested.

The payload passed to your callback is an OrderedDict with the following keys:

r         : R_ENTITY, R_FEED, etc # the type of existing resource
lid       : <name>                # the local name of the
                                  # existing resource
id        : <GUID>                # the global Id of the
                                  # existing resource
epId      : <GUID>                # the global Id of your agent

Note

Resource types are defined in IoticAgent.Core.Const module

Example

def duplicated_callback(args):
    print(args)
...
client.register_callback_created(duplicated_callback)

This would print out something like the following on re-creation of an R_ENTITY

OrderedDict([(u'lid', u'new_thing1'), (u'r', 1),
             (u'epId', u'ffd47b75ea786f55c76e337cdc47665a'),
             (u'id', u'3f11df0a09588a6a1a9732e3837765f8')]))
register_callback_reassigned(func, serialised=True)

Register a callback for resource reassignment. This will be called when any resource is reassigned to or from your agent. If serialised is not set, the callbacks might arrive in a different order to they were requested.

The payload passed to your callback is an OrderedDict with the following keys:

r         : R_ENTITY, R_FEED, etc # the type of resource reassigned
lid       : <name>                # the local name of the resource
epId      : <GUID>                # the global Id of the agent the
                                  # resource has been reassigned *to*
id        : <GUID>                # the global Id of the resource

Note

Resource types are defined in IoticAgent.Core.Const module

Note

You can check whether this is an assign “in” or “out” by comparing the epId with your current agent id, using the IOT.Client.agent_id property. If it’s the same it’s a reassign to you.

Example

def reassigned_callback(args):
    print(args)
...
client.register_callback_reassigned(reassigned_callback)

This would print out something like the following on assignment of an R_ENTITY to:

OrderedDict([(u'lid', u'moved_thing'),
             (u'r', 1),
             (u'epId', u'5a8d603ee757133d66d99875d0584c72'),
             (u'id', u'4448993b44738411de5fe2a6cf32d957')])
register_callback_renamed(func, serialised=True)

Register a callback for resource rename. This will be called when any resource is renamed within your agent.

If serialised is not set, the callbacks might arrive in a different order to they were requested.

The payload passed to your callback is an OrderedDict with the following keys

r         : R_ENTITY, R_FEED, etc # the type of resource deleted
lid       : <name>                # the new local name of the resource
oldLid    : <name>                # the old local name of the resource
id        : <GUID>                # the global Id of the resource

Note

Resource types are defined in IoticAgent.Core.Const module

Example

def renamed_callback(args):
    print(args)
...
client.register_callback_renamed(renamed_callback)

This would print out something like the following on renaming of an R_ENTITY

OrderedDict([(u'lid', u'new_name'),
             (u'r', 1),
             (u'oldLid', u'old_name'),
             (u'id', u'4448993b44738411de5fe2a6cf32d957')])
register_callback_subscribed(callback)

Register a callback for new subscription. This gets called whenever one of your things subscribes to something else.

Note

It is not called when whenever something else subscribes to your thing.

The payload passed to your callback is either a IoticAgent.IOT.RemotePoint module RemoteControl or RemoteFeed instance.

register_callback_subscription(callback)

Register a callback for subscription count change notification. This gets called whenever something else subscribes to your thing.

Note

It is not called when you subscribe to something else.

The payload passed to your callback is an OrderedDict with the following keys

r         : R_FEED or R_CONTROL # the type of the point
lid       : <name>              # the local name of your *Point*
entityLid : <name>              # the local name of your *Thing*
subCount  : <count>             # the total number of remote Things
                                # that subscribe to your point

Example

def subscription_callback(args):
    print(args)
...
client.register_callback_subscription(subscription_callback)

This would print out something like the following

OrderedDict([('r', 2), ('lid', 'My_First_Point'),
             ('entityLid', 'My_First_Thing'), ('subCount', 13)])
register_catchall_controlreq(callback, callback_parsed=None)

Registers a callback that is called for all control requests received by your Thing

Example

def controlreq_callback(data):
    print(data)
...
client.register_catchall_controlreq(controlreq_callback)
Parameters:
  • callback – the function name that you want to be called on receipt of a new control request
  • callback_parsed (function reference, optional) – callback function to invoke on receipt of a control ask/tell. This is equivalent to callback except the dict includes the parsed key which holds the set of values in a IoticAgent.IOT.Point module PointDataObject instance. If both callback_parsed and callback have been specified, the former takes precedence and callback is only called if the point data could not be parsed according to its current value description.

More details on the contents of the data dictionary for controls see IoticAgent.IOT.Thing module create_control

register_catchall_feeddata(callback, callback_parsed=None)

Registers a callback that is called for all feeddata your Thing receives

Example

def feeddata_callback(data):
    print(data)
...
client.register_catchall_feeddata(feeddata_callback)
Parameters:
  • callback – the function name that you want to be called on receipt of new feed data
  • callback_parsed (function reference, optional) – callback function to invoke on receipt of feed data. This is equivalent to callback except the dict includes the parsed key which holds the set of values in a IoticAgent.IOT.Point module PointDataObject instance. If both callback_parsed and callback have been specified, the former takes precedence and callback is only called if the point data could not be parsed according to its current value description.

Note

callback_parsed can only be used if auto_encode_decode is enabled for the client instance.

More details on the contents of the data dictionary for feeds see IoticAgent.IOT.Thing module Thing.follow.

save_config()

Save the config, update the seqnum & default language

search(text=None, lang=None, location=None, unit=None, limit=50, offset=0, reduced=False, scope=<SearchScope.PUBLIC: 'public'>)

Search the Iotic Space for public Things with metadata matching the search parameters: text, lang(uage), location, unit, limit, offset. Note that only things which have at least one point defined can be found.

Returns:Dict of results as below (first with reduced=False, second with reduced=True)
# reduced=False returns dict similar to below
{
    "2b2d8b068e404861b19f9e060877e002": {
        "long": -1.74803,
        "lat": 52.4539,
        "label": "Weather Station #2",
        "owner": "3bbf307b43b1460289fe707619dece3d",
        "points": {
            "a300cc90147f4e2990195639de0af201": {
                "label": "Feed 201",
                "type": "Feed",
                "storesRecent": true
            },
            "a300cc90147f4e2990195639de0af202": {
                "label": "Feed 202",
                "type": "Feed",
                "storesRecent": false
            }
        }
    },
    "76a3b24b02d34f20b675257624b0e001": {
        "long": 0.716356,
        "lat": 52.244384,
        "label": "Weather Station #1",
        "owner": "3bbf307b43b1460289fe707619dece3d",
        "points": {
            "fb1a4a4dbb2642ab9f836892da93f101": {
                "label": "My weather feed",
                "type": "Feed",
                "storesRecent": false
            },
            "fb1a4a4dbb2642ab9f836892da93c102": {
                "label": None,
                "type": "Control",
                "storesRecent": false
            }
        }
    }
}
# reduced=True returns dict similar to below
{
    "2b2d8b068e404861b19f9e060877e002": {
        "a300cc90147f4e2990195639de0af201": "Feed",
        "a300cc90147f4e2990195639de0af202": "Feed"
    },
    "76a3b24b02d34f20b675257624b0e001": {
        "fb1a4a4dbb2642ab9f836892da93f101": "Feed",
        "fb1a4a4dbb2642ab9f836892da93f102": "Control"
    }
}

OR

Raises:
  • IOTException – Infrastructure problem detected
  • LinkException – Communications problem between you and the infrastructure
Parameters:
  • text (string, optional) – The text to search for. Label and description will be searched for both Thing and Point and each word will be used as a tag search too. Text search is case-insensitive. Tag search is language neutral.
  • lang (string, optional) – The two-character ISO 639-1 language code to search in, e.g. “en” “fr”. Language is used to limit search to only labels and descriptions in that language. You will only get labels in that language back from search and then only if there are any in that language.
  • location (dictionary, optional) – Latitude, longitude and radius to search within. All values are float, Radius is in kilometers (km). E.g. {“lat”=1.2345, “long”=54.321, “radius”=6.789}. If text has not been specified, radius can at most be 25km.
  • unit (string, optional) – Valid URL of a unit in an ontology. Or use a constant from the IoticAgent.Units module class
  • limit (integer, optional) – Return this many search results
  • offset (integer, optional) – Return results starting at this offset - good for paging.
  • reduced (boolean, optional) – If true, return the reduced results just containing points and their type.
  • scope (optional) – Whether to perform PUBLIC, LOCAL (container level) or LOCAL_OWN (container level restricted to own things) search. Check the IoticAgent.IOT.Client module Client.local_meta) flag to determine whether local metadata functionality is available. (Note that PUBLIC and LOCAL_OWN scopes are always available.)
search_located(text=None, lang=None, location=None, unit=None, limit=100, offset=0, scope=<SearchScope.PUBLIC: 'public'>)

See IoticAgent.IOT.Client module Client.search for general documentation. Provides a thing-only result set comprised only of things which have a location set, e.g.:

{
    # Keyed by thing id
    '2b2d8b068e404861b19f9e060877e002':
        # location (g, lat & long), label (l, optional)
        {'g': (52.4539, -1.74803), 'l': 'Weather Station #2'},
    '76a3b24b02d34f20b675257624b0e001':
        {'g': (52.244384, 0.716356), 'l': None},
    '76a3b24b02d34f20b675257624b0e004':
        {'g': (52.245384, 0.717356), 'l': 'Gasometer'},
    '76a3b24b02d34f20b675257624b0e005':
        {'g': (52.245384, 0.717356), 'l': 'Zepellin'}
}
search_minimal(text=None, lang=None, location=None, unit=None, limit=100, offset=0, scope=<SearchScope.PUBLIC: 'public'>)

See IoticAgent.IOT.Client module Client.search for general documentation. Returns just a list of the id’s of matching things.

[
    '2b2d8b068e404861b19f9e060877e002',
    '76a3b24b02d34f20b675257624b0e001',
    '76a3b24b02d34f20b675257624b0e004',
    '76a3b24b02d34f20b675257624b0e005',
]
search_property(props, limit=50, offset=0, type_=<SearchType.FULL: 'full'>, scope=<SearchScope.PUBLIC: 'public'>, lang=None, with_pointless=False)

Search the Iotic Space for public Things with metadata matching the properties list, given as predicate-object tuples, with a third member denoting an XSD type if the object type is not among [str, int, float, bool]. Language-specific strings are specified with a suffix of two @’s and a two-letter language code, e.g. ‘@@en’.

Returns:Dict of results as below (with type_=SearchType.FULL; see shorthand methods for examples of other search type results)
{
    "2b2d8b068e404861b19f9e060877e002": {
        "long": -1.74803,
        "lat": 52.4539,
        "label": "Weather Station #2",
        "owner": "3bbf307b43b1460289fe707619dece3d",
        "points": {
            "a300cc90147f4e2990195639de0af201": {
                "label": "Feed 201",
                "type": "Feed",
                "storesRecent": true
            },
            "a300cc90147f4e2990195639de0af202": {
                "label": "Feed 202",
                "type": "Feed",
                "storesRecent": false
            }
        }
    },
    "76a3b24b02d34f20b675257624b0e001": {
        "long": 0.716356,
        "lat": 52.244384,
        "label": "Weather Station #1",
        "owner": "3bbf307b43b1460289fe707619dece3d",
        "points": {
            "fb1a4a4dbb2642ab9f836892da93f101": {
                "label": "My weather feed",
                "type": "Feed",
                "storesRecent": false
            },
            "fb1a4a4dbb2642ab9f836892da93c102": {
                "label": None,
                "type": "Control",
                "storesRecent": false
            }
        }
    }
}

OR

Raises:
  • IOTException – Infrastructure problem detected
  • LinkException – Communications problem between you and the infrastructure
Parameters:
  • props (list(tuple)) – The properties (or single property) to search for
  • limit (integer, optional) – Return this many search results
  • offset (integer, optional) – Return results starting at this offset - good for paging.
  • type (optional) – What kind of search to perform, FULL, REDUCED, LOCATED, or MINIMAL. See above for sample FULL results. See shorthand methods for sample REDUCED, LOCATED, and MINIMAL results.
  • scope (optional) – Whether to perform PUBLIC, LOCAL (container level) or LOCAL_OWN (container level restricted to own things) search. Check the IoticAgent.IOT.Client module Client.local_meta) flag to determine whether local metadata functionality is available. (Note that PUBLIC and LOCAL_OWN scopes are always available.)
  • lang (string, optional) – The language in which to return entity and point labels. Defaults to the metadata library’s default language.
  • with_pointless (bool, optional) – Whether to return entities that do not advertise any points (default False)
search_property_located(props, limit=100, offset=0, scope=<SearchScope.PUBLIC: 'public'>, lang=None, with_pointless=False)

Shorthand for search_property() from the IoticAgent.IOT.Client module with type_=SearchType.LOCATED. Provides a thing-only result set comprised only of things which have a location set, e.g.:

{
    # Keyed by thing id
    '2b2d8b068e404861b19f9e060877e002':
        # location (g, lat & long), label (l, optional)
        {'g': (52.4539, -1.74803), 'l': 'Weather Station #2'},
    '76a3b24b02d34f20b675257624b0e001':
        {'g': (52.244384, 0.716356), 'l': None},
    '76a3b24b02d34f20b675257624b0e004':
        {'g': (52.245384, 0.717356), 'l': 'Gasometer'},
    '76a3b24b02d34f20b675257624b0e005':
        {'g': (52.245384, 0.717356), 'l': 'Zepellin'}
}
search_property_minimal(props, limit=100, offset=0, scope=<SearchScope.PUBLIC: 'public'>, with_pointless=False)

Shorthand for search_property() from the IoticAgent.IOT.Client module with type_=SearchType.MINIMAL. Returns just a list of the id’s of matching things.

[
    '2b2d8b068e404861b19f9e060877e002',
    '76a3b24b02d34f20b675257624b0e001',
    '76a3b24b02d34f20b675257624b0e004',
    '76a3b24b02d34f20b675257624b0e005',
]
search_property_reduced(props, limit=100, offset=0, scope=<SearchScope.PUBLIC: 'public'>, with_pointless=False)

Shorthand for search_property() from the IoticAgent.IOT.Client module with type_=SearchType.REDUCED. Sample results:

{
    "2b2d8b068e404861b19f9e060877e002": {
        "a300cc90147f4e2990195639de0af201": "Feed",
        "a300cc90147f4e2990195639de0af202": "Feed"
    },
    "76a3b24b02d34f20b675257624b0e001": {
        "fb1a4a4dbb2642ab9f836892da93f101": "Feed",
        "fb1a4a4dbb2642ab9f836892da93f102": "Control"
    }
}
search_reduced(text=None, lang=None, location=None, unit=None, limit=100, offset=0, scope=<SearchScope.PUBLIC: 'public'>)

Shorthand for search() from the IoticAgent.IOT.Client module with reduced=True

simulate_feeddata(feedid, data, mime=None, time=None)

Simulate the last feeddata received for given feedid. Calls the registered callback for the feed with the last recieved feed data. Allows you to test your code without having to wait for the remote thing to share again.

Parameters:
  • feedid (string) – local id of your Feed
  • data (optional) – The data you want to use to simulate the arrival of remote feed data
  • mime (string, optional) – The mime type of your data. See also IoticAgent.IOT.Point module Feed.share
  • time (datetime, optional) – UTC timestamp for share. See also: IoticAgent.IOT.Point module Feed.share
start()
Open a connection to Iotic Space. start() is called by __enter__ which allows the python with syntax to
be used.

Example 0:

Calling start() implicitly using with. Minimal example with no exception handling:

with IOT.Client(config="my_script.ini") as client:
    client.create_thing("my_thing")

Example 1

Calling start() implicitly using with. This handles the finally for you. Recommended:

try:
    with IOT.Client(config="my_script.ini") as client:
        try:
            client.create_thing("my_thing")
        except IOTException as exc:
            # handle exception
except Exception as exc:  # not possible to connect
    print(exc)
    import sys
    sys.exit(1)

Example 2

Calling start() explicitly (no with). Be careful, you have to put a finally in your try blocks otherwise your client might remain connected.

try:
    client = IOT.Client(config="my_script.ini")
    # wire up callbacks here
    client.start()
except Exception as exc:
    print(exc)
    import sys
    sys.exit(1)

try:
    client.create_thing("my_thing")
except IOTException as exc:
    # handle individual exception
finally:
    client.stop()
Returns:This Client instance
Raises:Exception
stop()

Close the connection to Iotic Space. stop() is called by __exit()__ allowing the python with syntax to be used. See IoticAgent.IOT.Client module client start

sync_timeout

Value of iot.sync_request_timeout configuration option. Used by all synchronous requests to limit total request wait time.