kepconfig.iot_gateway.agent

agent exposes an API to allow modifications (add, delete, modify) to Iot Gateway agent objects within the Kepware Configuration API

  1# -------------------------------------------------------------------------
  2# Copyright (c) PTC Inc. and/or all its affiliates. All rights reserved.
  3# See License.txt in the project root for
  4# license information.
  5# --------------------------------------------------------------------------
  6
  7
  8r"""`agent` exposes an API to allow modifications (add, delete, modify) to 
  9Iot Gateway agent objects within the Kepware Configuration API
 10"""
 11
 12# from .. import connection 
 13from typing import Union
 14from ..connection import server
 15from .. import iot_gateway as IOT
 16from ..error import KepError, KepHTTPError
 17import inspect
 18from ..utils import _url_parse_object
 19
 20IOT_ROOT_URL = '/project/_iot_gateway'
 21MQTT_CLIENT_URL = '/mqtt_clients'
 22REST_CLIENT_URL = '/rest_clients'
 23REST_SERVER_URL = '/rest_servers'
 24THINGWORX_URL = '/thingworx_clients'
 25
 26def _create_url(agent_type, agent = None):
 27    '''Creates url object for the "agent" branch of Kepware's project tree. Used 
 28    to build a part of Kepware Configuration API URL structure
 29
 30    Returns the agent specific url when a value is passed as the agent name.
 31    '''
 32
 33    if agent == None:
 34        if agent_type == IOT.MQTT_CLIENT_AGENT:
 35            return '{}{}'.format(IOT_ROOT_URL, MQTT_CLIENT_URL)
 36        elif agent_type == IOT.REST_CLIENT_AGENT:
 37            return '{}{}'.format(IOT_ROOT_URL, REST_CLIENT_URL)
 38        elif agent_type == IOT.REST_SERVER_AGENT:
 39            return '{}{}'.format(IOT_ROOT_URL, REST_SERVER_URL)
 40        elif agent_type == IOT.THINGWORX_AGENT:
 41            return '{}{}'.format(IOT_ROOT_URL, THINGWORX_URL)
 42        else:
 43            pass
 44    else:
 45        if agent_type == IOT.MQTT_CLIENT_AGENT:
 46            return '{}{}/{}'.format(IOT_ROOT_URL, MQTT_CLIENT_URL, _url_parse_object(agent))
 47        elif agent_type == IOT.REST_CLIENT_AGENT:
 48            return '{}{}/{}'.format(IOT_ROOT_URL, REST_CLIENT_URL, _url_parse_object(agent))
 49        elif agent_type == IOT.REST_SERVER_AGENT:
 50            return '{}{}/{}'.format(IOT_ROOT_URL, REST_SERVER_URL,_url_parse_object(agent))
 51        elif agent_type == IOT.THINGWORX_AGENT:
 52            return '{}{}/{}'.format(IOT_ROOT_URL, THINGWORX_URL, _url_parse_object(agent))
 53        else:
 54            pass
 55
 56
 57def add_iot_agent(server: server, DATA: Union[dict, list], agent_type: str = None) -> Union[bool, list]:
 58    '''Add a  `"agent"` or multiple `"agent"` objects of a specific type to Kepware's IoT Gateway. Can be used to pass children of an
 59    agent object such as iot items. This allows you to create an agent and iot items if desired. Multiple Agents need to be of the 
 60    same type.
 61
 62    Additionally it can be used to pass a list of agents and it's children to be added all at once.
 63
 64    :param server: instance of the `server` class
 65    :param DATA: Dict or List of Dicts of the agent and it's children
 66    expected by Kepware Configuration API
 67    :param agent_type: *(optional)* agent type to add to IoT Gateway. Only needed if not existing in `"DATA"`. Valid values are 
 68    `MQTT Client`, `REST Client` or `REST Server`
 69
 70    :return: True - If a "HTTP 201 - Created" is received from Kepware server
 71    :return: If a "HTTP 207 - Multi-Status" is received from Kepware with a list of dict error responses for all 
 72    iot agents added that failed.
 73
 74    :raises KepHTTPError: If urllib provides an HTTPError
 75    :raises KepURLError: If urllib provides an URLError
 76    '''
 77    
 78    if agent_type == None:
 79        try:
 80            # If it's a list, use the first agents type
 81            if isinstance(DATA, list): agent_type = DATA[0]['iot_gateway.AGENTTYPES_TYPE']
 82            else: agent_type = DATA['iot_gateway.AGENTTYPES_TYPE']
 83        except KeyError as err:
 84            err_msg = 'Error: No agent identified in DATA | Key Error: {}'.format(err)
 85            raise KepError(err_msg)
 86    
 87    r = server._config_add(server.url + _create_url(agent_type), DATA)
 88    if r.code == 201: return True 
 89    elif r.code == 207:
 90        errors = [] 
 91        for item in r.payload:
 92            if item['code'] != 201:
 93                errors.append(item)
 94        return errors
 95    else: raise KepHTTPError(r.url, r.code, r.msg, r.hdrs, r.payload)
 96
 97def del_iot_agent(server: server, agent: str, agent_type: str) -> bool:
 98    '''Delete a `"agent"` object in Kepware. This will delete all children as well
 99    
100    :param server: instance of the `server` class
101    :param agent: name of IoT Agent to delete
102    :param agent_type: *(optional)* agent type to delete in IoT Gateway. Valid values are 
103    `MQTT Client`, `REST Client` or `REST Server`
104
105    :return: True - If a "HTTP 200 - OK" is received from Kepware server
106
107    :raises KepHTTPError: If urllib provides an HTTPError
108    :raises KepURLError: If urllib provides an URLError
109    '''
110    r = server._config_del(server.url + _create_url(agent_type, agent))
111    if r.code == 200: return True 
112    else: raise KepHTTPError(r.url, r.code, r.msg, r.hdrs, r.payload)
113
114def modify_iot_agent(server: server, DATA: dict, *, agent: str = None, agent_type: str = None, force: bool = False) -> bool:
115    '''Modify a `"agent"` object and it's properties in Kepware. If a `"agent"` is not provided as an input,
116    you need to identify the agent in the *'common.ALLTYPES_NAME'* property field in the `"DATA"`. It will 
117    assume that is the agent that is to be modified.
118
119    :param server: instance of the `server` class
120    :param DATA: Dict of the iot agent properties to be modified.
121    :param agent: *(optional)* name of IoT agent to modify. Only needed if not existing in `"DATA"`
122    :param agent_type: *(optional)* agent type to modify. Only needed if not existing in `"DATA"`. Valid values are 
123    `MQTT Client`, `REST Client` or `REST Server`
124    :param force: *(optional)* if True, will force the configuration update to the Kepware server
125
126    :return: True - If a "HTTP 200 - OK" is received from Kepware server
127
128    :raises KepHTTPError: If urllib provides an HTTPError
129    :raises KepURLError: If urllib provides an URLError
130    '''
131    
132    agent_data = server._force_update_check(force, DATA)
133    
134    if agent_type == None:
135        if 'iot_gateway.AGENTTYPES_TYPE' in DATA:
136            agent_type = DATA['iot_gateway.AGENTTYPES_TYPE']
137        else:
138            err_msg = 'Error: Error with {}: {}'.format(inspect.currentframe().f_code.co_name, 'No Agent type defined.')
139            raise KepError(err_msg)
140    if agent == None:
141        try:
142            r = server._config_update(server.url + _create_url(agent_type, agent_data['common.ALLTYPES_NAME']), agent_data)
143            if r.code == 200: return True 
144            else: raise KepHTTPError(r.url, r.code, r.msg, r.hdrs, r.payload)
145        except KeyError as err:
146            err_msg = 'Error: No agent identified in DATA | Key Error: {}'.format(err)
147            raise KepError(err_msg)
148    else:
149        r = server._config_update(server.url + _create_url(agent_type, agent), agent_data)
150        if r.code == 200: return True 
151        else: raise KepHTTPError(r.url, r.code, r.msg, r.hdrs, r.payload)
152
153def get_iot_agent(server: server, agent: str, agent_type: str) -> dict:
154    '''Returns the properties of the `"agent"` object.
155    
156    :param server: instance of the `server` class
157    :param DATA: Dict of the iot agent properties to be modified.
158    :param agent: name of IoT agent to retrieve
159    :param agent_type: agent type. Valid values are `MQTT Client`, `REST Client` or `REST Server`
160
161    :return: Dict of properties for the iot agent requested
162
163    :raises KepHTTPError: If urllib provides an HTTPError
164    :raises KepURLError: If urllib provides an URLError
165    '''
166    r = server._config_get(server.url + _create_url(agent_type, agent))
167    return r.payload
168
169def get_all_iot_agents(server: server, agent_type: str, *, options: dict = None) -> list:
170    '''Returns the properties of all `"agent"` objects for a specific agent type. Returned object is JSON list.
171    
172    :param server: instance of the `server` class
173    :param agent_type: agent type. Valid values are `MQTT Client`, `REST Client` or `REST Server`
174    :param options: *(optional)* Dict of parameters to filter, sort or pagenate the list of IoT agents. Options are 'filter', 
175    'sortOrder', 'sortProperty', 'pageNumber', and 'pageSize'. Only used when exchange_name is not defined.
176
177    :return: list of properties for all IoT agents requested
178
179    :raises KepHTTPError: If urllib provides an HTTPError
180    :raises KepURLError: If urllib provides an URLError
181    '''
182    r = server._config_get(f'{server.url}{_create_url(agent_type)}', params= options)
183    return r.payload
IOT_ROOT_URL = '/project/_iot_gateway'
MQTT_CLIENT_URL = '/mqtt_clients'
REST_CLIENT_URL = '/rest_clients'
REST_SERVER_URL = '/rest_servers'
THINGWORX_URL = '/thingworx_clients'
def add_iot_agent( server: kepconfig.connection.server, DATA: Union[dict, list], agent_type: str = None) -> Union[bool, list]:
58def add_iot_agent(server: server, DATA: Union[dict, list], agent_type: str = None) -> Union[bool, list]:
59    '''Add a  `"agent"` or multiple `"agent"` objects of a specific type to Kepware's IoT Gateway. Can be used to pass children of an
60    agent object such as iot items. This allows you to create an agent and iot items if desired. Multiple Agents need to be of the 
61    same type.
62
63    Additionally it can be used to pass a list of agents and it's children to be added all at once.
64
65    :param server: instance of the `server` class
66    :param DATA: Dict or List of Dicts of the agent and it's children
67    expected by Kepware Configuration API
68    :param agent_type: *(optional)* agent type to add to IoT Gateway. Only needed if not existing in `"DATA"`. Valid values are 
69    `MQTT Client`, `REST Client` or `REST Server`
70
71    :return: True - If a "HTTP 201 - Created" is received from Kepware server
72    :return: If a "HTTP 207 - Multi-Status" is received from Kepware with a list of dict error responses for all 
73    iot agents added that failed.
74
75    :raises KepHTTPError: If urllib provides an HTTPError
76    :raises KepURLError: If urllib provides an URLError
77    '''
78    
79    if agent_type == None:
80        try:
81            # If it's a list, use the first agents type
82            if isinstance(DATA, list): agent_type = DATA[0]['iot_gateway.AGENTTYPES_TYPE']
83            else: agent_type = DATA['iot_gateway.AGENTTYPES_TYPE']
84        except KeyError as err:
85            err_msg = 'Error: No agent identified in DATA | Key Error: {}'.format(err)
86            raise KepError(err_msg)
87    
88    r = server._config_add(server.url + _create_url(agent_type), DATA)
89    if r.code == 201: return True 
90    elif r.code == 207:
91        errors = [] 
92        for item in r.payload:
93            if item['code'] != 201:
94                errors.append(item)
95        return errors
96    else: raise KepHTTPError(r.url, r.code, r.msg, r.hdrs, r.payload)

Add a "agent" or multiple "agent" objects of a specific type to Kepware's IoT Gateway. Can be used to pass children of an agent object such as iot items. This allows you to create an agent and iot items if desired. Multiple Agents need to be of the same type.

Additionally it can be used to pass a list of agents and it's children to be added all at once.

Parameters
  • server: instance of the server class
  • DATA: Dict or List of Dicts of the agent and it's children expected by Kepware Configuration API
  • agent_type: (optional) agent type to add to IoT Gateway. Only needed if not existing in "DATA". Valid values are MQTT Client, REST Client or REST Server
Returns

True - If a "HTTP 201 - Created" is received from Kepware server

Returns

If a "HTTP 207 - Multi-Status" is received from Kepware with a list of dict error responses for all iot agents added that failed.

Raises
  • KepHTTPError: If urllib provides an HTTPError
  • KepURLError: If urllib provides an URLError
def del_iot_agent(server: kepconfig.connection.server, agent: str, agent_type: str) -> bool:
 98def del_iot_agent(server: server, agent: str, agent_type: str) -> bool:
 99    '''Delete a `"agent"` object in Kepware. This will delete all children as well
100    
101    :param server: instance of the `server` class
102    :param agent: name of IoT Agent to delete
103    :param agent_type: *(optional)* agent type to delete in IoT Gateway. Valid values are 
104    `MQTT Client`, `REST Client` or `REST Server`
105
106    :return: True - If a "HTTP 200 - OK" is received from Kepware server
107
108    :raises KepHTTPError: If urllib provides an HTTPError
109    :raises KepURLError: If urllib provides an URLError
110    '''
111    r = server._config_del(server.url + _create_url(agent_type, agent))
112    if r.code == 200: return True 
113    else: raise KepHTTPError(r.url, r.code, r.msg, r.hdrs, r.payload)

Delete a "agent" object in Kepware. This will delete all children as well

Parameters
  • server: instance of the server class
  • agent: name of IoT Agent to delete
  • agent_type: (optional) agent type to delete in IoT Gateway. Valid values are MQTT Client, REST Client or REST Server
Returns

True - If a "HTTP 200 - OK" is received from Kepware server

Raises
  • KepHTTPError: If urllib provides an HTTPError
  • KepURLError: If urllib provides an URLError
def modify_iot_agent( server: kepconfig.connection.server, DATA: dict, *, agent: str = None, agent_type: str = None, force: bool = False) -> bool:
115def modify_iot_agent(server: server, DATA: dict, *, agent: str = None, agent_type: str = None, force: bool = False) -> bool:
116    '''Modify a `"agent"` object and it's properties in Kepware. If a `"agent"` is not provided as an input,
117    you need to identify the agent in the *'common.ALLTYPES_NAME'* property field in the `"DATA"`. It will 
118    assume that is the agent that is to be modified.
119
120    :param server: instance of the `server` class
121    :param DATA: Dict of the iot agent properties to be modified.
122    :param agent: *(optional)* name of IoT agent to modify. Only needed if not existing in `"DATA"`
123    :param agent_type: *(optional)* agent type to modify. Only needed if not existing in `"DATA"`. Valid values are 
124    `MQTT Client`, `REST Client` or `REST Server`
125    :param force: *(optional)* if True, will force the configuration update to the Kepware server
126
127    :return: True - If a "HTTP 200 - OK" is received from Kepware server
128
129    :raises KepHTTPError: If urllib provides an HTTPError
130    :raises KepURLError: If urllib provides an URLError
131    '''
132    
133    agent_data = server._force_update_check(force, DATA)
134    
135    if agent_type == None:
136        if 'iot_gateway.AGENTTYPES_TYPE' in DATA:
137            agent_type = DATA['iot_gateway.AGENTTYPES_TYPE']
138        else:
139            err_msg = 'Error: Error with {}: {}'.format(inspect.currentframe().f_code.co_name, 'No Agent type defined.')
140            raise KepError(err_msg)
141    if agent == None:
142        try:
143            r = server._config_update(server.url + _create_url(agent_type, agent_data['common.ALLTYPES_NAME']), agent_data)
144            if r.code == 200: return True 
145            else: raise KepHTTPError(r.url, r.code, r.msg, r.hdrs, r.payload)
146        except KeyError as err:
147            err_msg = 'Error: No agent identified in DATA | Key Error: {}'.format(err)
148            raise KepError(err_msg)
149    else:
150        r = server._config_update(server.url + _create_url(agent_type, agent), agent_data)
151        if r.code == 200: return True 
152        else: raise KepHTTPError(r.url, r.code, r.msg, r.hdrs, r.payload)

Modify a "agent" object and it's properties in Kepware. If a "agent" is not provided as an input, you need to identify the agent in the 'common.ALLTYPES_NAME' property field in the "DATA". It will assume that is the agent that is to be modified.

Parameters
  • server: instance of the server class
  • DATA: Dict of the iot agent properties to be modified.
  • agent: (optional) name of IoT agent to modify. Only needed if not existing in "DATA"
  • agent_type: (optional) agent type to modify. Only needed if not existing in "DATA". Valid values are MQTT Client, REST Client or REST Server
  • force: (optional) if True, will force the configuration update to the Kepware server
Returns

True - If a "HTTP 200 - OK" is received from Kepware server

Raises
  • KepHTTPError: If urllib provides an HTTPError
  • KepURLError: If urllib provides an URLError
def get_iot_agent(server: kepconfig.connection.server, agent: str, agent_type: str) -> dict:
154def get_iot_agent(server: server, agent: str, agent_type: str) -> dict:
155    '''Returns the properties of the `"agent"` object.
156    
157    :param server: instance of the `server` class
158    :param DATA: Dict of the iot agent properties to be modified.
159    :param agent: name of IoT agent to retrieve
160    :param agent_type: agent type. Valid values are `MQTT Client`, `REST Client` or `REST Server`
161
162    :return: Dict of properties for the iot agent requested
163
164    :raises KepHTTPError: If urllib provides an HTTPError
165    :raises KepURLError: If urllib provides an URLError
166    '''
167    r = server._config_get(server.url + _create_url(agent_type, agent))
168    return r.payload

Returns the properties of the "agent" object.

Parameters
  • server: instance of the server class
  • DATA: Dict of the iot agent properties to be modified.
  • agent: name of IoT agent to retrieve
  • agent_type: agent type. Valid values are MQTT Client, REST Client or REST Server
Returns

Dict of properties for the iot agent requested

Raises
  • KepHTTPError: If urllib provides an HTTPError
  • KepURLError: If urllib provides an URLError
def get_all_iot_agents( server: kepconfig.connection.server, agent_type: str, *, options: dict = None) -> list:
170def get_all_iot_agents(server: server, agent_type: str, *, options: dict = None) -> list:
171    '''Returns the properties of all `"agent"` objects for a specific agent type. Returned object is JSON list.
172    
173    :param server: instance of the `server` class
174    :param agent_type: agent type. Valid values are `MQTT Client`, `REST Client` or `REST Server`
175    :param options: *(optional)* Dict of parameters to filter, sort or pagenate the list of IoT agents. Options are 'filter', 
176    'sortOrder', 'sortProperty', 'pageNumber', and 'pageSize'. Only used when exchange_name is not defined.
177
178    :return: list of properties for all IoT agents requested
179
180    :raises KepHTTPError: If urllib provides an HTTPError
181    :raises KepURLError: If urllib provides an URLError
182    '''
183    r = server._config_get(f'{server.url}{_create_url(agent_type)}', params= options)
184    return r.payload

Returns the properties of all "agent" objects for a specific agent type. Returned object is JSON list.

Parameters
  • server: instance of the server class
  • agent_type: agent type. Valid values are MQTT Client, REST Client or REST Server
  • options: (optional) Dict of parameters to filter, sort or pagenate the list of IoT agents. Options are 'filter', 'sortOrder', 'sortProperty', 'pageNumber', and 'pageSize'. Only used when exchange_name is not defined.
Returns

list of properties for all IoT agents requested

Raises
  • KepHTTPError: If urllib provides an HTTPError
  • KepURLError: If urllib provides an URLError