Coverage for tutorials/ngsi_v2/e1_virtual_weatherstation/e1_virtual_weatherstation_solution.py: 0%

17 statements  

« prev     ^ index     » next       coverage.py v7.10.2, created at 2025-08-05 11:07 +0000

1""" 

2# # Exercise 1: Virtual Weather-Station 

3 

4# Create a virtual IoT device that simulates the ambient temperature and 

5# publishes it via MQTT. The simulation function is already predefined. 

6# This exercise gives a simple introduction to the communication via MQTT. 

7 

8# The input sections are marked with 'ToDo' 

9 

10# #### Steps to complete: 

11# 1. Set up the missing parameters in the parameter section 

12# 2. Create an MQTT client using the paho-mqtt package with mqtt.Client() 

13# 3. Define a callback function that will be executed when the client 

14# receives message on a subscribed topic. It should decode your message 

15# and store the information for later in our history 

16# `history_weather_station` 

17# 4. Subscribe to the topic that the device will publish to 

18# 5. Create a function that publishes the simulated temperature `t_amb` and 

19# the corresponding simulation time `t_sim `via MQTT as a JSON 

20# 6. Run the simulation and plot 

21""" 

22 

23# ## Import packages 

24import json 

25import time 

26from urllib.parse import urlparse 

27from uuid import uuid4 

28import matplotlib.pyplot as plt 

29import paho.mqtt.client as mqtt 

30 

31# import simulation model 

32from tutorials.ngsi_v2.simulation_model import SimulationModel 

33 

34# ## Parameters 

35# ToDo: Enter your mqtt broker url and port, e.g. mqtt://test.mosquitto.org:1883. 

36MQTT_BROKER_URL = "mqtt://test.mosquitto.org:1883" 

37# ToDo: If required, enter your username and password. 

38MQTT_USER = "" 

39MQTT_PW = "" 

40 

41# ToDo: Create a unique topic that your weather station will publish on, 

42# e.g. by using a uuid. 

43UNIQUE_ID = str(uuid4()) 

44TOPIC_WEATHER_STATION = f"fiware_workshop/{UNIQUE_ID}/weather_station" 

45 

46# set parameters for the temperature simulation 

47TEMPERATURE_MAX = 10 # maximal ambient temperature 

48TEMPERATURE_MIN = -5 # minimal ambient temperature 

49 

50T_SIM_START = 0 # simulation start time in seconds 

51T_SIM_END = 24 * 60 * 60 # simulation end time in seconds 

52COM_STEP = 60 * 60 # 60 min communication step in seconds 

53 

54# ## Main script 

55if __name__ == "__main__": 

56 # instantiate simulation model 

57 sim_model = SimulationModel( 

58 t_start=T_SIM_START, 

59 t_end=T_SIM_END, 

60 temp_max=TEMPERATURE_MAX, 

61 temp_min=TEMPERATURE_MIN, 

62 ) 

63 

64 # define a list for storing historical data 

65 history_weather_station = [] 

66 

67 # ToDo: Create an MQTTv5 client with paho-mqtt. 

68 mqttc = mqtt.Client( 

69 protocol=mqtt.MQTTv5, callback_api_version=mqtt.CallbackAPIVersion.VERSION2 

70 ) 

71 # set user data if required 

72 mqttc.username_pw_set(username=MQTT_USER, password=MQTT_PW) 

73 

74 # ToDo: Define a callback function that will be executed when the client 

75 # receives message on a subscribed topic. It should decode your message 

76 # and store the information for later in our history. 

77 # Note: Do not change the function's signature! 

78 def on_message(client, userdata, msg): 

79 """ 

80 Callback function for incoming messages 

81 """ 

82 # decode the payload 

83 payload = msg.payload.decode("utf-8") 

84 # ToDo: Parse the payload using the `json` package and write it to 

85 # the history. 

86 history_weather_station.append(json.loads(payload)) 

87 

88 # add your callback function to the client. You can either use a global 

89 # or a topic specific callback with `mqttc.message_callback_add()` 

90 mqttc.on_message = on_message 

91 

92 # ToDo: Connect to the mqtt broker and subscribe to your topic. 

93 mqtt_url = urlparse(MQTT_BROKER_URL) 

94 mqttc.connect( 

95 host=mqtt_url.hostname, 

96 port=mqtt_url.port, 

97 keepalive=60, 

98 bind_address="", 

99 bind_port=0, 

100 clean_start=mqtt.MQTT_CLEAN_START_FIRST_ONLY, 

101 properties=None, 

102 ) 

103 

104 # ToDo: Print and subscribe to the weather station topic. 

105 print(f"WeatherStation topic:\n {TOPIC_WEATHER_STATION}") 

106 mqttc.subscribe(topic=TOPIC_WEATHER_STATION) 

107 

108 # create a non-blocking thread for mqtt communication 

109 mqttc.loop_start() 

110 

111 # ToDo: Create a loop that publishes every 0.2 seconds a message to the broker 

112 # that holds the simulation time "t_sim" and the corresponding temperature 

113 # "t_amb". 

114 for t_sim in range( 

115 sim_model.t_start, int(sim_model.t_end + COM_STEP), int(COM_STEP) 

116 ): 

117 # ToDo: Publish the simulated ambient temperature. 

118 mqttc.publish( 

119 topic=TOPIC_WEATHER_STATION, 

120 payload=json.dumps({"t_amb": sim_model.t_amb, "t_sim": sim_model.t_sim}), 

121 ) 

122 

123 # simulation step for next loop 

124 sim_model.do_step(int(t_sim + COM_STEP)) 

125 time.sleep(0.2) 

126 

127 # close the mqtt listening thread 

128 mqttc.loop_stop() 

129 # disconnect the mqtt device 

130 mqttc.disconnect() 

131 

132 # plot results 

133 fig, ax = plt.subplots() 

134 t_simulation = [item["t_sim"] / 3600 for item in history_weather_station] 

135 temperature = [item["t_amb"] for item in history_weather_station] 

136 ax.plot(t_simulation, temperature) 

137 ax.set_xlabel("time in h") 

138 ax.set_ylabel("ambient temperature in °C") 

139 plt.show()