Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

237 update and refactor examples #278

Merged
merged 56 commits into from
Jul 9, 2024
Merged
Show file tree
Hide file tree
Changes from 45 commits
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
02817a3
style: fix typos in basic examples
Maghnie Feb 1, 2024
1f4abe4
fix: replace deprecated pydantic function
Maghnie Feb 1, 2024
d1b4fb8
style: clarify log messages in e01
Maghnie Feb 1, 2024
2be25e3
fix: use workaround for queries bug
Maghnie Feb 1, 2024
9485200
docs: clarify example subscriptions URL
Maghnie Feb 1, 2024
5803712
docs: clarify aim of subscription example
Maghnie Feb 1, 2024
7a0998a
fix: update deprecated pydantic function
Maghnie Feb 1, 2024
12448b7
docs: fix broken link to subscriptions docs
Maghnie Feb 1, 2024
38af45c
docs: link to web server tutorial
Maghnie Feb 1, 2024
24379e2
Add latest changes
Maghnie Apr 17, 2024
d8a56b1
fix: fix typos and pep-8
Apr 17, 2024
804d8a9
Merge branch 'master' into 237-update-and-refactor-examples
Apr 24, 2024
0f5717c
fix: fix deprecated methods
Apr 24, 2024
9cebb59
fix: fix deprecated methods in e05
Apr 30, 2024
6a4e36b
format: fix pep 8 errors
Apr 30, 2024
cf7d371
format: reformat the sentences and fix typos in e05
Apr 30, 2024
0325eae
fix: revert the default service path
Apr 30, 2024
441f343
fix: reverse kilometer to kilometre for pydantic
Apr 30, 2024
60ff6b9
fix: fix deprecated methods in e08
WaltherTrgovac May 1, 2024
291c0b8
feat: remove milliseconds from logger
WaltherTrgovac May 7, 2024
31cafa0
feat: change print statements for better readability in e10
WaltherTrgovac May 7, 2024
74f28b6
format: format e10 for consistency
WaltherTrgovac May 7, 2024
fbe7576
fix: remove redundant subscription_id
WaltherTrgovac May 7, 2024
23ecb6b
fix: fix typos and pep 8 errors in e07
WaltherTrgovac May 8, 2024
bee4278
feat: remove milliseconds from logger and use only printf statements …
WaltherTrgovac May 8, 2024
5ff889e
fix: fix f string in cb.py
WaltherTrgovac May 8, 2024
912a48b
fix: fix logger output in e01
WaltherTrgovac May 8, 2024
9c5fb58
Merge branch 'master' into 237-update-and-refactor-examples
WaltherTrgovac May 14, 2024
53e578b
feature: reformat logger date and remove milliseconds
WaltherTrgovac May 16, 2024
e5bcbdf
feat: remove module name from logging
WaltherTrgovac May 16, 2024
286fe15
fix: change entity ids to the standard form in e01
WaltherTrgovac May 16, 2024
a93d735
format: reformat mqtt notifications in e04
WaltherTrgovac May 21, 2024
877c252
format: reformat comments in e03
WaltherTrgovac May 21, 2024
220af0c
fix: remove unused imports in e04
WaltherTrgovac May 21, 2024
a7b77e7
format: reformat e05
WaltherTrgovac May 22, 2024
0832912
format: adjust entity ids in e07
WaltherTrgovac May 28, 2024
3bf11ac
feat: remove module name from the logger in mqtt client
WaltherTrgovac May 29, 2024
d46f296
fix: fix difference between logger and actual data in fiware
WaltherTrgovac Jun 5, 2024
54b4cf0
format: fix typos in e08
WaltherTrgovac Jun 5, 2024
f2dc6eb
format: reformat mqtt callback functions in e04 and e08
Jun 12, 2024
ddb08b1
format: reformat mqtt callbacks and print statements in e09
Jun 12, 2024
c690a72
format: reformat on_message callback function in e04
Jun 12, 2024
fdb468e
fix: adjust f strings to python 3.9
Jun 18, 2024
b7a30d4
fix: fix missing parameters in clear_context_broker
Jun 18, 2024
0045371
chore: reformat README.md
Jun 18, 2024
8001b3a
feat: adjust path finding for .env.filip
Jul 3, 2024
d4e7b0d
fix: restore .env.filip settings
Jul 3, 2024
5c64d58
chore: fix the position of .env.filip
djs0109 Jul 9, 2024
9aeff2d
chore: remove unused variables in .env.filip.EXAMPLE
djs0109 Jul 9, 2024
070787a
chore: remove unused .env.filip in basic
djs0109 Jul 9, 2024
e6e2620
chore: add MQTT Broker URL to config
djs0109 Jul 9, 2024
47db06f
chore: use settings in examples
djs0109 Jul 9, 2024
380bf36
Merge branch 'master' into 237-update-and-refactor-examples
djs0109 Jul 9, 2024
ded1f43
chore: convert mqtt url to str
djs0109 Jul 9, 2024
3038d1d
fix: error caused by update
djs0109 Jul 9, 2024
a24273c
docs: add hint regarding .env.filip in readme
djs0109 Jul 9, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 22 additions & 19 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -1,41 +1,44 @@
# Examples

This directory contains examples to support to teach you how to use FiLiP to
build smart solutions based on FIWARE.
This directory contains examples to support you how to use FiLiP to
build smart solutions based on FIWARE.
In order to execute the examples you need a working FIWARE instance. For more details
look into the [required prerequisites](https://github.com/RWTH-EBC/FiLiP?tab=readme-ov-file#prerequisites) of the
library.
Each example should be executable with only small adjustments according to
your FIWARE instance, e.g. URL settings
your FIWARE instance, e.g. URL settings.

The following topics are covered:

#### How to use the clients and use general settings?

- [http-clients](https://github.com/RWTH-EBC/FiLiP/blob/master/examples/basics/e01_http_clients.py)
- [logging](https://github.com/RWTH-EBC/FiLiP/blob/master/examples/basics/e11_logging.py)
- [settings-management](https://github.com/RWTH-EBC/FiLiP/blob/master/examples/basics/e11_logging.py)
- [http-clients](./basics/e01_http_clients.py)
- [logging](./basics/e11_logging.py)
- [settings-management](./basics/e12_settings.py)

#### How to model context and interact with context broker Orion?
#### How to model context and interact with Orion Context Broker?

- [Context Basics](https://github.com/RWTH-EBC/FiLiP/blob/master/examples/ngsi_v2/e01_ngsi_v2_context_basics.py)
- [Context Relationships](https://github.com/RWTH-EBC/FiLiP/blob/master/examples/ngsi_v2/e02_ngsi_v2_context_relationships.py)
- [Context HTTP Subscriptions](https://github.com/RWTH-EBC/FiLiP/blob/master/examples/ngsi_v2/e03_ngsi_v2_context_subscriptions_http.py)
- [Context MQTT Subscriptions](https://github.com/RWTH-EBC/FiLiP/blob/master/examples/ngsi_v2/e03_ngsi_v2_context_subscriptions_mqtt.py)
- [Context Registrations](https://github.com/RWTH-EBC/FiLiP/blob/master/examples/ngsi_v2/e05_ngsi_v2_context_registrations.py)
- [Context Model Generation](https://github.com/RWTH-EBC/FiLiP/blob/master/examples/ngsi_v2/e06_ngsi_v2_autogenerate_context_data_models.py)
- [Context Basics](./ngsi_v2/e01_ngsi_v2_context_basics.py)
- [Context Relationships](./ngsi_v2/e02_ngsi_v2_context_relationships.py)
- [Context HTTP Subscriptions](./ngsi_v2/e03_ngsi_v2_context_subscriptions_http.py)
- [Context MQTT Subscriptions](./ngsi_v2/e04_ngsi_v2_context_subscriptions_mqtt.py)
- [Context Registrations](./ngsi_v2/e05_ngsi_v2_context_registrations.py)
- [Context Model Generation](./ngsi_v2/e06_ngsi_v2_autogenerate_context_data_models.py)

#### How to interact with IoT-Agent?

- [IoT Basics](https://github.com/RWTH-EBC/FiLiP/blob/master/examples/ngsi_v2/e07_ngsi_v2_iota_basics.py)
- [IoT Paho MQTT](https://github.com/RWTH-EBC/FiLiP/blob/master/examples/ngsi_v2/e08_ngsi_v2_iota_paho_mqtt.py)
- [IoT FiLiP MQTT](https://github.com/RWTH-EBC/FiLiP/blob/master/examples/ngsi_v2/e09_ngsi_v2_iota_filip_mqtt.py)
- [IoT Basics](./ngsi_v2/e07_ngsi_v2_iota_basics.py)
- [IoT Paho MQTT](./ngsi_v2/e08_ngsi_v2_iota_paho_mqtt.py)
- [IoT FiLiP MQTT](./ngsi_v2/e09_ngsi_v2_iota_filip_mqtt.py)
(We implemented this for magic MQTT-Topic handling)

#### How to handle time series data and interact with QuantumLeap?

- [Time Series Data](https://github.com/RWTH-EBC/FiLiP/blob/master/examples/ngsi_v2/e10_ngsi_v2_quantumleap.py)
- [Time Series Data](./ngsi_v2/e10_ngsi_v2_quantumleap.py)
with QuantumLeap

#### How to use ontologies for semantic system modelling?

- [Semantics](https://github.com/RWTH-EBC/FiLiP/tree/master/examples/ngsi_v2/e11_ngsi_v2_semantics)
- [Use-case specific data modeling](https://github.com/RWTH-EBC/FiLiP/tree/master/examples/ngsi_v2/e12_ngsi_v2_use_case_models.py)
- [Semantics](./ngsi_v2/e11_ngsi_v2_semantics)
- [Use-case specific data modeling](./ngsi_v2/e12_ngsi_v2_use_case_models.py)

32 changes: 16 additions & 16 deletions examples/basics/e01_http_clients.py
WaltherTrgovac marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
# Host address of QuantumLeap
QL_URL = "http://localhost:8668"
#
# You can here also change the used Fiware service
# Here you can also change the used Fiware service
# FIWARE-Service
service = 'filip'
# FIWARE-Servicepath
Expand All @@ -34,40 +34,40 @@

# # 1 FiwareHeader
#
# First a create a fiware header that you want to work with
# First create a fiware header that you want to work with
# For more details on the headers check the official documentation:
# https://fiware-orion.readthedocs.io/en/master/user/multitenancy/index.html
#
# In short a fiware header specifies a location in Fiware where the
# In short, a fiware header specifies a location in Fiware where the
# created entities will be saved and requests are executed.
# It can be thought of as a separated subdirectory where you work in.
# It can be thought of as a separate subdirectory where you work in.
fiware_header = FiwareHeader(service='filip',
service_path='/example')

# # 2 Client modes
# You can run the clients in different modes:
#
# ## 2.1 Run it as pure python object.
# ## 2.1 Run it as a pure python object.
#
# This will open and close a connection each time you use a function.
cb_client = ContextBrokerClient(url="http://134.130.166.184:1026",
cb_client = ContextBrokerClient(url=CB_URL,
fiware_header=fiware_header)
print(f"OCB Version: {cb_client.get_version()}")

# ## 2.2 Run the client via the python's context protocol.
# ## 2.2 Run the client via python's context protocol.
#
# This will initialize requests.session that the client will reuse for
# each function.
# Formally, this usually lead to an performance boost because the
# connection was reused reused. The client and its connection will be
# closed after the end of the with-statement. However, thanks to urllib3
# the keep-alive and session reuse is handled totally automatically.
# Formerly, this usually lead to a performance boost because the
# connection was reused. The client and its connection are
# closed after the end of the with-statement. However, thanks to urllib3,
# the keep-alive and session reuse are handled totally automatically.
with ContextBrokerClient(fiware_header=fiware_header) as cb_client:
print(f"OCB Version: {cb_client.get_version()}")

# ## 2.3 Run the client with an externally provided requests.Session object
#
# This mode is recommend when you want to reuse requests.Session and mix
# This mode is recommended when you want to reuse requests.Session and mix
# different clients. It is also useful in combination with OAuth2Session
# objects that handle authentication mechanisms and third party libraries.
# Please be aware that you need to do the session handling yourself.
Expand All @@ -88,12 +88,12 @@

# # 4 URL
#
# Additional to the FiwareHeader each client needs an URL, that points
# Additional to the FiwareHeader each client needs a URL that points
# to the Fiware-server.
#
# ## 4.1 Environment variables
#
# As shown above the client does not need to be given explicitly. If no URL
# As shown above, the client does not need to be given explicitly. If no URL
# is given to the client, it is extracted from the environment variables
#
# ## 4.2 Direct Provision
Expand All @@ -109,7 +109,7 @@
# # 5 Combined Client
#
# The library also contains a client (HttpClient) that contains all the
# particular clients as bundle.
# particular clients as a bundle.
# It works almost the same as the other agents but takes a config. This
# can be either a dict or the path to a json file:

Expand All @@ -128,4 +128,4 @@
# Close client
iota_client.close()
cb_client.close()
ql_client.close()
ql_client.close()
6 changes: 3 additions & 3 deletions examples/basics/e11_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@
# therefore reuses the streams of the root logger.
"""

# import python's build in logging implementation
# import python's built-in logging implementation
import logging
# import an api client from filip as example
from filip.clients.ngsi_v2 import ContextBrokerClient
# setting up the basic configuration of the logging system. Please check the
# official documentation and the functions docstrings for more details.
# Handling for 'handlers' in the logging system is not trivial.
# It is also import to know that this function should only be called once in
# It is also important to know that this function should only be called once in
# your application. Since FiLiP is an SDK that should help to implement other
# services we do not call this function anywhere in our code.
# services, we do not call this function anywhere in our code.
# Hence, it is up to the user to configure the logging system.

# In this example we will simply change the log level and the log format.
Expand Down
11 changes: 3 additions & 8 deletions examples/basics/e12_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,16 @@
# configuration settings. Using *.json config-files or environment
# variables. You can also use the .env.filip file to provide the variables
#
# Feel free to play around with the settings and the check how
# Feel free to play around with the settings and see how
# the urls and header parameter will be checked and/or automatically
# guessed based on the provided information.

# Note: Although Urls are also guessed the safest is to set the service url
# Note: Although URLs are also guessed, the safest option is to set the service url
# directly
"""
import os







if __name__ == '__main__':

# # 1 Example using environment variables
Expand All @@ -27,4 +22,4 @@
os.environ["IOTA_URL"] = "http://localhost:4041"

from filip import settings
print(settings.json(indent=2))
print(settings.model_dump_json(indent=2))
72 changes: 38 additions & 34 deletions examples/ngsi_v2/e01_ngsi_v2_context_basics.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
# Example how to use Entity-models and interact with teh orion ContextBroker
# Example how to use Entity-models and interact with the Orion ContextBroker
"""

# ## Import packages
Expand All @@ -13,27 +13,27 @@

# ## Parameters
#
# To run this example you need a working Fiware v2 setup with a context-broker
# You can here set the address:
# To run this example, you need a working Fiware v2 setup with a context-broker
# You can set the address here:
#
# Host address of Context Broker
CB_URL = "http://localhost:1026"

# You can here also change the used Fiware service
# You can also change the used Fiware service
# FIWARE-Service
SERVICE = 'filip'
# FIWARE-Servicepath
# FIWARE-Service path
SERVICE_PATH = '/example'

# Setting up logging
logging.basicConfig(
level='INFO',
format='%(asctime)s %(name)s %(levelname)s: %(message)s')
format='%(asctime)s %(name)s %(levelname)s: %(message)s',
datefmt='%d-%m-%Y %H:%M:%S')
logger = logging.getLogger(__name__)


if __name__ == "__main__":

# # 1 Setup Client
#
# create the client, for more details view the example: e01_http_clients.py
Expand All @@ -43,8 +43,8 @@
fiware_header=fiware_header)
# View version
for key, value in cb_client.get_version().items():
logger.info("Context broker version" + value["version"] + " at url " +
cb_client.base_url)
logger.info(f"Context broker version: {value['version']} at url: "
f"{cb_client.base_url}")

# # 2 Create Entities
#
Expand All @@ -54,18 +54,18 @@
#
# ### 2.1.1 Passing a dict:
#
room1 = {"id": "Room1",
"type": "Room",
"temperature": {"value": 11,
"type": "Float"},
"pressure": {"value": 111,
"type": "Integer"}
}
room1_entity = ContextEntity(**room1)
room1_dictionary = {"id": "urn:ngsi-ld:Room:001",
"type": "Room",
"temperature": {"value": 11,
"type": "Float"},
"pressure": {"value": 111,
"type": "Integer"}
}
room1_entity = ContextEntity(**room1_dictionary)

# ### 2.1.2 Using the constructor and interfaces
#
room2_entity = ContextEntity(id="Room2", type="Room")
room2_entity = ContextEntity(id="urn:ngsi-ld:Room:002", type="Room")
temp_attr = NamedContextAttribute(name="temperature", value=22,
type=DataType.FLOAT)
pressure_attr = NamedContextAttribute(name="pressure", value=222,
Expand All @@ -74,33 +74,37 @@

# ## 2.2 Post Entities
#
print(cb_client.get_entity_list())
logger.info(f'Entity list before posting to CB: {cb_client.get_entity_list()}')
cb_client.post_entity(entity=room1_entity)
cb_client.post_entity(entity=room2_entity)

# # 3 Access entities in Fiware
#
# Get all entities from context broker
logger.info(cb_client.get_entity_list())
logger.info(f'Entity list after posting to CB: {cb_client.get_entity_list()}')

# Get entities by id
logger.info(cb_client.get_entity_list(entity_ids=["Room1"]))
logger.info(f'Entities with ID "urn:ngsi-ld:Room:001": '
f'{cb_client.get_entity_list(entity_ids=["urn:ngsi-ld:Room:001"])}')

# Get entities by type
logger.info(cb_client.get_entity_list(entity_types=["Room"]))
logger.info(f'Entities by type "Room": {cb_client.get_entity_list(entity_types=["Room"])}')

# Get entities by id pattern
logger.info(cb_client.get_entity_list(id_pattern="^Room[2-5]"))
# The regular expression filters the rooms that have the id number 2 through 5
# with the prefix 'urn:ngsi-ld:Room:'
logger.info(f'Entities with id pattern "^urn:ngsi-ld:Room:00[2-5]": '
f'{cb_client.get_entity_list(id_pattern="^urn:ngsi-ld:Room:00[2-5]")}')

# Get entities by query expression
query = QueryString(qs=[('temperature', '>', 22)])
logger.info(cb_client.get_entity_list(q=query))
query = QueryString(qs=[('temperature', '>=', 22)])
logger.info(f'Entities with temperature >= 22: {cb_client.get_entity_list(q=query)}')

# Get attributes of entities
logger.info(cb_client.get_entity_attributes(entity_id="Room1"))
logger.info(f'Attributes of entities: {cb_client.get_entity_attributes(entity_id="urn:ngsi-ld:Room:001")}')

# Accessing non existing ids or attributes will always throw an request
# error
# Trying to access non-existing ids or attributes will always throw
# a request error

# # 4 Changing Entities
#
Expand All @@ -112,8 +116,8 @@
# ### 4.1.1 Updating directly
#
# Using the Filip interface, we can update different properties of our
# entity directly in the live version in FIWARE, here are listed a few
# examples of what is possible:
# entity directly in the live version in FIWARE. A few examples of what
# is possible are listed here:

# Updating value of an attribute of an entity
logger.info(cb_client.update_attribute_value(entity_id=room1_entity.id,
Expand All @@ -130,7 +134,7 @@
# Hereby it is tried to only make changes that were done locally,
# keeping as much of the current live state as possible

# when accessing an attribute a new object is created. We need to
# When accessing an attribute a new object is created. We need to
# manually transmit the made changes.
temp_attr = room2_entity.get_attribute("temperature")
temp_attr.value = 15
Expand All @@ -146,5 +150,5 @@
# To delete an entry in Fiware, we can call:
cb_client.delete_entity(entity_id=room2_entity.id,
entity_type=room2_entity.type)
# cb_client.delete_entity(entity_id=room1_entity.id,
# entity_type=room1_entity.type)
cb_client.delete_entity(entity_id=room1_entity.id,
entity_type=room1_entity.type)
Loading