Skip to content

Commit 1db146a

Browse files
committed
docs: update reader
1 parent 2002154 commit 1db146a

File tree

1 file changed

+19
-51
lines changed

1 file changed

+19
-51
lines changed

src/reader.py

Lines changed: 19 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
# Obtains data. It connects to the MQTT broker and subscribes to the topics 'data/meas' and 'rfid/tde'. The script sends a message to #
44
# the topic 'data/meas' with the parameters 'pos_x', 'pos_y', 'pos_z', and 'moist'. The script receives the RFID data from the topic #
55
# 'rfid/tde' and writes the data to a file. #
6-
# Filepath: RFID-Reader-FX7500/src/reader.py #
76
# =================================================================================================================================== #
87

98

@@ -14,8 +13,7 @@
1413
import time # Time access and conversions. #
1514
import paho.mqtt.client as mqtt # MQTT version 3.1/3.1.1 client class. #
1615
import os # Miscellaneous operating system interfaces. #
17-
import datetime # Basic date and time types. #
18-
import pytz # World Timezone Definitions. #
16+
import pytz # World Timezone Definitions. #
1917
# =================================================================================================================================== #
2018

2119

@@ -53,7 +51,7 @@ def filename_generator(tag: int, freq: float, distance: float, obstacle: int) ->
5351
Returns:
5452
str: The generated filename.
5553
"""
56-
tags = ['Belt_G2iL', 'Belt_9XM', 'Dogbone_Monza 4D', 'Frog_3D', 'Miniweb_G2iL', 'Shortdipole_G2iL', 'Shortdipole_Monza_R6',
54+
tags = ['Belt_G2iL', 'Belt_9XM', 'Dogbone_Monza_4D', 'Frog_3D', 'Miniweb_G2iL', 'Shortdipole_G2iL', 'Shortdipole_Monza_R6',
5755
'Spine', 'Trap', 'Viper', 'Web_G2iL', 'Web_U9']
5856
obstacles = ['None', 'Cardboard', 'Metal', 'Wood', 'Human_Hand', 'Human_Body', 'Soil_(Dry)']
5957

@@ -71,7 +69,7 @@ def filename_generator(tag: int, freq: float, distance: float, obstacle: int) ->
7169
raise ValueError(f"Invalid distance: {distance}")
7270
# Get the current date and time with timezone
7371
tz = pytz.timezone('CET')
74-
current_time = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
72+
current_time = datetime.datetime.now(tz).strftime("%Y%m%d_%H%M%S")
7573

7674
return f"./data/03022025/{current_time}_{tags[tag]}_{freq}MHz_{distance}m_{obstacles[obstacle]}.csv"
7775

@@ -88,24 +86,15 @@ def validate_filename(filename: str) -> bool:
8886
try:
8987
directory = os.path.dirname(filename)
9088
if not os.path.exists(directory):
91-
os.makedirs(directory, exist_ok=True)
92-
print(f"Directory created: {directory}")
93-
else:
94-
print(f"Directory already exists: {directory}")
89+
os.makedirs(directory)
9590
# Try opening the file to ensure it can be written to
96-
with open(filename, 'a+') as f:
97-
if os.path.getsize(filename) == 0:
98-
headers = [
99-
'n_group', 'eventNum', 'peakRssi', 'phase', 'channel', 'pos_x', 'pos_y', 'pos_z', 'moist',
100-
'antenna', 'reads', 'idHex', 'format', 'PC', 'CRC', 'MAC', 'hostName', 'time_utc', 'type'
101-
]
102-
f.write(','.join(headers) + '\n')
103-
print(f"Filename is valid: {filename}")
91+
with open(filename, 'w') as f:
92+
pass
10493
return True
10594
except Exception as e:
10695
print(f"Error validating filename: {e}")
10796
return False
108-
97+
10998
def on_connect(client: mqtt.Client, userdata: dict, flags: dict, reason_code: int, properties: dict) -> None:
11099
"""
111100
This function is called when the client is connected to the MQTT broker.
@@ -124,7 +113,6 @@ def on_connect(client: mqtt.Client, userdata: dict, flags: dict, reason_code: in
124113
client.subscribe("data/meas")
125114
client.subscribe("rfid/tde")
126115

127-
128116
def on_message(client: mqtt.Client, userdata: dict, msg: mqtt.MQTTMessage, filename: str) -> None:
129117
"""
130118
This function is called when a message is received from the MQTT broker.
@@ -139,29 +127,11 @@ def on_message(client: mqtt.Client, userdata: dict, msg: mqtt.MQTTMessage, filen
139127
None.
140128
"""
141129
if msg.topic == 'rfid/tde':
142-
userdata['n_reads'] += 1
143-
data = json.loads(msg.payload)
144-
time_utc = time.strptime(data["timestamp"], '%Y-%m-%dT%H:%M:%S.%f%z')
145-
time_utc = time.mktime(time_utc) + float(data["timestamp"][-9:-5]) + 6 * 3600.
146-
print(msg.topic + f' ({datetime.datetime.fromtimestamp(time_utc)}) ' + str(msg.payload))
147-
148-
pos_y = userdata['pos_y'] + (.0 if 'e200' in data['data']['idHex'] else -.11)
149-
n_group, pos_x, pos_z, moist = userdata['n_group'], userdata['pos_x'], userdata['pos_z'], userdata['moist']
150-
with open(filename, 'a+') as f:
151-
f.write(
152-
'{n_group},\t{eventNum},\t{peakRssi},\t{phase},\t{channel},\t{pos_x},\t{pos_y},\t{pos_z},\t'
153-
'{moist},\t{antenna},\t{reads},\t{idHex},\t{format},\t{PC},\t{CRC},\t{MAC},\t{hostName}'.format(
154-
**data['data'], n_group=n_group, pos_y=pos_y, pos_x=pos_x, pos_z=pos_z, moist=moist
155-
) + f',\t{time_utc},\t{data["type"]}\n'
156-
)
157-
if userdata['n_reads'] > 100:
158-
# client.publish('rfid/c', b'{"command": "stop", "command_id": "321", "payload": {}}')
159-
# client.disconnect()
160-
pass
130+
with open(filename, 'a') as f:
131+
f.write(msg.payload.decode() + '\n')
161132
elif msg.topic == 'data/meas':
162-
userdata['n_group'] += 1
163-
userdata.update(json.loads(msg.payload))
164-
# mosquitto_pub -h 158.109.74.35 -p 1883 -t 'data/meas' -m '{"pos_x": 0, "pos_y": -.5, "pos_z": 0, "moist": 0}'
133+
data = json.loads(msg.payload.decode())
134+
userdata.update(data)
165135
# =================================================================================================================================== #
166136

167137

@@ -180,9 +150,11 @@ def read(filename: str, server_ip: str, server_port: int, duration: float) -> No
180150
Returns:
181151
None
182152
"""
183-
validate_filename(filename)
153+
if not validate_filename(filename):
154+
raise ValueError("Invalid filename or directory cannot be created.")
155+
184156
state = {'n_reads': 0, 'n_group': 0, 'pos_x': .0, 'pos_y': -1.205, 'pos_z': .0, 'depth': .0, 'moist': .0} # angle
185-
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
157+
mqttc = mqtt.Client()
186158
mqttc.on_connect = on_connect
187159
mqttc.on_message = lambda client, userdata, msg: on_message(client, userdata, msg, filename)
188160
mqttc.user_data_set(state)
@@ -192,16 +164,12 @@ def read(filename: str, server_ip: str, server_port: int, duration: float) -> No
192164

193165
try:
194166
mqttc.loop_start()
195-
start_time = time.monotonic()
196-
while time.monotonic() - start_time < duration:
197-
mqttc.publish('data/meas', '{{"pos_x": {pos_x}, "pos_y": {pos_y}, "pos_z": {pos_z},'
198-
' "moist": {moist}}}'.format(**state).encode())
199-
time.sleep(1.)
200-
# mqttc.loop_forever()
167+
time.sleep(duration)
201168
except FileNotFoundError as e:
202-
print(e)
169+
print(f"File not found: {e}")
203170
finally:
204-
mqttc.publish('rfid/c', b'{"command": "stop", "command_id": "321", "payload": {}}')
205171
mqttc.loop_stop()
172+
mqttc.disconnect()
173+
206174
print('FINISH')
207175
# =================================================================================================================================== #

0 commit comments

Comments
 (0)