Skip to content

Commit 30674f6

Browse files
author
Walther
committed
fix: change deprecated methods and fix typos
1 parent 8a58574 commit 30674f6

File tree

1 file changed

+59
-59
lines changed

1 file changed

+59
-59
lines changed

tutorials/ngsi_v2/e4_iot_thermal_zone_sensors/e4_iot_thermal_zone_sensors_solution.py

+59-59
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
"""
22
# # Exercise 4: Virtual Thermal Zone
33
4-
# Create two virtual IoT device. One of them represents the temperature
4+
# Create two virtual IoT devices. One of them represents the temperature
55
# sensor for the air temperature of a the thermal zone, whereas the second
6-
# represents a virtual weather station. Both devices publish there values to
6+
# represents a virtual weather station. Both devices publish their values to
77
# the platform via MQTT. Use the simulation model of
88
# e1_virtual_weatherstation.py
99
#
1010
# The input sections are marked with 'ToDo'
1111
#
1212
# #### Steps to complete:
1313
# 1. Set up the missing parameters in the parameter section
14-
# 2. Create a service group and two devices
14+
# 2. Create a service group and two corresponding devices
1515
# 3. Provision the service group and the devices
1616
# 4. Create an MQTT client using the filip.client.mqtt package and register
1717
# your service group and your devices
@@ -46,20 +46,20 @@
4646
IOTA_URL = "http://localhost:4041"
4747
# ToDo: Enter your mqtt broker url, e.g mqtt://test.mosquitto.org:1883
4848
MQTT_BROKER_URL = "mqtt://localhost:1883"
49-
# ToDo: If required enter your username and password
49+
# ToDo: If required, enter your username and password
5050
MQTT_USER = ""
51-
MQTT_PW = ""
51+
MQTT_PW = ""
5252
# FIWARE-Service
5353
SERVICE = 'filip_tutorial'
54-
# FIWARE-Servicepath
54+
# FIWARE-Service path
5555
# ToDo: Change the name of your service-path to something unique. If you run
56-
# on a shared instance this very important in order to avoid user
57-
# collisions. You will use this service path through the whole tutorial.
58-
# If you forget to change it an error will be raised!
56+
# on a shared instance, this is very important in order to avoid user
57+
# collisions. You will use this service path throughout the whole tutorial.
58+
# If you forget to change it, an error will raise!
5959
SERVICE_PATH = '/your_path'
6060
APIKEY = SERVICE_PATH.strip('/')
6161

62-
# Path to json-files to device configuration data for follow up exercises
62+
# Path to json-files to device configuration data for follow-up exercises
6363
WRITE_GROUPS_FILEPATH = Path(
6464
"../e4_iot_thermal_zone_sensors_solution_groups.json")
6565
WRITE_DEVICES_FILEPATH = Path(
@@ -94,17 +94,16 @@
9494
history_weather_station = []
9595
history_zone_temperature_sensor = []
9696

97-
# Create a service group and add it to your
97+
# create a service group and add it to your
9898
service_group = ServiceGroup(apikey=APIKEY,
9999
resource="/iot/json")
100100

101101
# ToDo: create two IoTA-MQTT devices for the weather station and the zone
102102
# temperature sensor. Also add the simulation time as `active attribute`
103103
# to each device!
104-
#
105104
# create the weather station device
106-
# create the simtime attribute and add during device creation
107-
t_sim = DeviceAttribute(name='simtime',
105+
# create the sim_time attribute and add it to the weather station's attributes
106+
t_sim = DeviceAttribute(name='sim_time',
108107
object_id='t_sim',
109108
type="Number")
110109

@@ -118,16 +117,16 @@
118117
commands=[])
119118

120119
# create a temperature attribute and add it via the api of the
121-
# `device`-model. Use the 't_amb' as `object_id`. `object_id` specifies
120+
# 'device'-model. Use the 't_amb' as 'object_id'. 'object_id' specifies
122121
# what key will be used in the MQTT Message payload
123122
t_amb = DeviceAttribute(name='temperature',
124123
object_id='t_amb',
125124
type="Number")
126125

127126
weather_station.add_attribute(t_amb)
128127

129-
# ToDo: create the zone temperature device add the t_sim attribute upon
130-
# creation
128+
# ToDo: Create the zone temperature device add the t_sim attribute upon
129+
# creation.
131130
zone_temperature_sensor = Device(device_id='device:002',
132131
entity_name='urn:ngsi-ld:TemperatureSensor:001',
133132
entity_type='TemperatureSensor',
@@ -137,52 +136,53 @@
137136
attributes=[t_sim],
138137
commands=[])
139138
# ToDo: Create the temperature attribute. Use the 't_zone' as `object_id`.
140-
# `object_id` specifies what key will be used in the MQTT Message payload
139+
# `object_id` specifies what key will be used in the MQTT Message payload.
141140
t_zone = DeviceAttribute(name='temperature',
142141
object_id='t_zone',
143142
type="Number")
143+
144144
zone_temperature_sensor.add_attribute(t_zone)
145145

146-
# ToDo: Create an IoTAClient
146+
# ToDo: Create an IoTAClient.
147147
iotac = IoTAClient(url=IOTA_URL, fiware_header=fiware_header)
148-
# ToDo: Provision service group and add it to your IoTAMQTTClient
148+
# ToDo: Provision service group and add it to your IoTAMQTTClient.
149149
iotac.post_group(service_group=service_group, update=True)
150-
# ToDo: Provision the devices at the IoTA-Agent
151-
# provision the WeatherStation device
150+
# ToDo: Provision the devices at the IoTA-Agent.
151+
# provision the weather station device
152152
iotac.post_device(device=weather_station, update=True)
153-
# ToDo: provision the zone temperature device
153+
# ToDo: Provision the zone temperature device.
154154
iotac.post_device(device=zone_temperature_sensor, update=True)
155155

156-
# ToDo: Check in the context broker if the entities corresponding to your
157-
# devices where correctly created
158-
# ToDo: Create a context broker client
156+
# ToDo: Create a context broker client.
157+
# ToDo: Check in the context broker whether the entities corresponding to your
158+
# devices were correctly created.
159159
cbc = ContextBrokerClient(url=CB_URL, fiware_header=fiware_header)
160-
# Get WeatherStation entity
161-
print(cbc.get_entity(weather_station.entity_name).json(indent=2))
162-
# Get ZoneTemperatureSensor entity
163-
print(cbc.get_entity(zone_temperature_sensor.entity_name).json(indent=2))
160+
# get weather station entity
161+
print(f"Weather station:\n{cbc.get_entity(weather_station.entity_name).model_dump_json(indent=2)}")
162+
# get zone temperature sensor entity
163+
print(f"Zone temperature sensor:\n{cbc.get_entity(zone_temperature_sensor.entity_name).model_dump_json(indent=2)}")
164164

165-
# ToDo: create an MQTTv5 client using filip.clients.mqtt.IoTAMQTTClient
165+
# ToDo: Create an MQTTv5 client using filip.clients.mqtt.IoTAMQTTClient.
166166
mqttc = IoTAMQTTClient(protocol=mqtt.MQTTv5)
167167
# set user data if required
168168
mqttc.username_pw_set(username=MQTT_USER, password=MQTT_PW)
169-
# ToDo: Register the service group with your MQTT-Client
169+
# ToDo: Register the service group with your MQTT-Client.
170170
mqttc.add_service_group(service_group=service_group)
171-
# ToDo: Register devices with your MQTT-Client
171+
# ToDo: Register devices with your MQTT-Client.
172172
# register the weather station
173173
mqttc.add_device(weather_station)
174-
# ToDo: register the zone temperature sensor
174+
# ToDo: register the zone temperature sensor.
175175
mqttc.add_device(zone_temperature_sensor)
176176

177-
# The IoTAMQTTClient automatically creates the outgoing topics from the
177+
# The IoTAMQTTClient automatically creates outgoing topics from the
178178
# device configuration during runtime. Hence, we need to construct them
179-
# manually in order to subscribe to them. This is usually not required as
180-
# only the platform should listen to incoming traffic.
181-
# if you want to listen subscribe to the following topics:
179+
# manually in order to subscribe to them. This is usually not required as
180+
# only the platform should listen to the incoming traffic.
181+
# If you want to listen subscribe to the following topics:
182182
# "/json/<APIKEY>/<weather_station.device_id>/attrs"
183183
# "/json/<APIKEY>/<zone_temperature_sensor.device_id>/attrs"
184184

185-
# ToDO: connect to the mqtt broker and subscribe to your topic
185+
# ToDO: Connect to the mqtt broker and subscribe to your topic.
186186
mqtt_url = urlparse(MQTT_BROKER_URL)
187187
mqttc.connect(host=mqtt_url.hostname,
188188
port=mqtt_url.port,
@@ -197,66 +197,66 @@
197197
# create a non-blocking thread for mqtt communication
198198
mqttc.loop_start()
199199

200-
# ToDo: Create a loop that publishes every second a message to the broker
201-
# that holds the simulation time "simtime" and the corresponding
202-
# temperature "temperature" the loop should. You may use the `object_id`
203-
# or the attribute name as key in your payload.
200+
# ToDo: Create a loop that publishes a message every 100 milliseconds
201+
# to the broker that holds the simulation time "sim_time" and the
202+
# corresponding temperature "temperature". You may use the 'object_id'
203+
# or the attribute name as a key in your payload.
204204
for t_sim in range(sim_model.t_start,
205205
sim_model.t_end + int(COM_STEP),
206206
int(COM_STEP)):
207207
# publish the simulated ambient temperature
208208
mqttc.publish(device_id=weather_station.device_id,
209209
payload={"temperature": sim_model.t_amb,
210-
"simtime": sim_model.t_sim})
210+
"sim_time": sim_model.t_sim})
211211

212-
# ToDo: publish the simulated zone temperature
212+
# ToDo: Publish the simulated zone temperature.
213213
mqttc.publish(device_id=zone_temperature_sensor.device_id,
214214
payload={"temperature": sim_model.t_zone,
215-
"simtime": sim_model.t_sim})
215+
"sim_time": sim_model.t_sim})
216216

217-
# simulation step for next loop
217+
# simulation step for the next loop
218218
sim_model.do_step(int(t_sim + COM_STEP))
219219
# wait for one second before publishing the next values
220-
time.sleep(1)
220+
time.sleep(0.1)
221221

222-
# Get corresponding entities and write values to history
222+
# get corresponding entities and store the data
223223
weather_station_entity = cbc.get_entity(
224224
entity_id=weather_station.entity_name,
225225
entity_type=weather_station.entity_type
226226
)
227227
# append the data to the local history
228228
history_weather_station.append(
229-
{"simtime": weather_station_entity.simtime.value,
229+
{"sim_time": weather_station_entity.sim_time.value,
230230
"temperature": weather_station_entity.temperature.value})
231231

232-
# ToDo: Get ZoneTemperatureSensor and write values to history
232+
# ToDo: Get zone temperature sensor and store the data.
233233
zone_temperature_sensor_entity = cbc.get_entity(
234234
entity_id=zone_temperature_sensor.entity_name,
235235
entity_type=zone_temperature_sensor.entity_type
236236
)
237237
history_zone_temperature_sensor.append(
238-
{"simtime": zone_temperature_sensor_entity.simtime.value,
238+
{"sim_time": zone_temperature_sensor_entity.sim_time.value,
239239
"temperature": zone_temperature_sensor_entity.temperature.value})
240240

241241
# close the mqtt listening thread
242242
mqttc.loop_stop()
243243
# disconnect the mqtt device
244244
mqttc.disconnect()
245245

246-
# plot results
246+
# plot the results
247247
fig, ax = plt.subplots()
248-
t_simulation = [item["simtime"] for item in history_weather_station]
248+
t_simulation = [item["sim_time"]/3600 for item in history_weather_station]
249249
temperature = [item["temperature"] for item in history_weather_station]
250250
ax.plot(t_simulation, temperature)
251-
ax.set_xlabel('time in s')
251+
ax.set_xlabel('time in h')
252252
ax.set_ylabel('ambient temperature in °C')
253253

254254
fig2, ax2 = plt.subplots()
255-
t_simulation = [item["simtime"] for item in history_zone_temperature_sensor]
255+
t_simulation = [item["sim_time"]/3600 for item in history_zone_temperature_sensor]
256256
temperature = [item["temperature"] for item in
257257
history_zone_temperature_sensor]
258258
ax2.plot(t_simulation, temperature)
259-
ax2.set_xlabel('time in s')
259+
ax2.set_xlabel('time in h')
260260
ax2.set_ylabel('zone temperature in °C')
261261

262262
plt.show()
@@ -266,14 +266,14 @@
266266
f"Wrong file extension! {WRITE_DEVICES_FILEPATH.suffix}"
267267
WRITE_DEVICES_FILEPATH.touch(exist_ok=True)
268268
with WRITE_DEVICES_FILEPATH.open('w', encoding='utf-8') as f:
269-
devices = [item.dict() for item in iotac.get_device_list()]
269+
devices = [item.model_dump() for item in iotac.get_device_list()]
270270
json.dump(devices, f, ensure_ascii=False, indent=2)
271271

272272
assert WRITE_GROUPS_FILEPATH.suffix == '.json', \
273273
f"Wrong file extension! {WRITE_GROUPS_FILEPATH.suffix}"
274274
WRITE_GROUPS_FILEPATH.touch(exist_ok=True)
275275
with WRITE_GROUPS_FILEPATH.open('w', encoding='utf-8') as f:
276-
groups = [item.dict() for item in iotac.get_group_list()]
276+
groups = [item.model_dump() for item in iotac.get_group_list()]
277277
json.dump(groups, f, ensure_ascii=False, indent=2)
278278

279279
clear_context_broker(url=CB_URL, fiware_header=fiware_header)

0 commit comments

Comments
 (0)