Skip to content

Commit b8012ed

Browse files
committed
ftespnow-server: Added JSON support, and write to dictionary functionality
Added the receive_to_json() function, that supports exporting received data to a JSON file, and the receive_to_dict() function, that returns the received data as a dictionary
1 parent a8288dd commit b8012ed

1 file changed

Lines changed: 73 additions & 1 deletion

File tree

  • micropython/ftespnow/ftespnow-server/ftespnow

micropython/ftespnow/ftespnow-server/ftespnow/server.py

Lines changed: 73 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,4 +130,76 @@ def receive_to_txt(self, target_file: str, mode: str='a') -> bool:
130130
f.writelines(data_list)
131131
return True
132132
except SyntaxError:
133-
raise
133+
raise
134+
135+
def receive_to_json(self, target_file: str, mode: str='a') -> bool:
136+
"""
137+
Write received `string` into a `.json` file.
138+
139+
Args:
140+
141+
target_file (str): Filepath of the destination file for the received data with file name and extension.
142+
143+
mode (str, optional): Editing mode
144+
145+
- `r` - Read only
146+
147+
- `w` - Write only (truncates file before writing)
148+
149+
- `x` - Create a new file and open it for writing (raises `FileExistsError` if file already exists)
150+
151+
- `a` - Append to the end of the file (default)
152+
153+
- `b` - Binary mode
154+
155+
- `t` - Text mode
156+
157+
- `+` - Update (read and write)
158+
159+
Read `open()`_ for more information
160+
161+
Returns:
162+
163+
received (bool): Confirmation flag (`True` if data was received, `False` otherwise)
164+
165+
.. _open(): https://docs.python.org/3/library/functions.html#open
166+
"""
167+
168+
if ".json" not in target_file: raise SyntaxError("File format must be .json")
169+
try:
170+
received: bool = False
171+
data: list | None = self.receive_message()
172+
if data == None: return received
173+
mac: str = str(data[0])
174+
message = json.loads(str(data[-1]))
175+
unparsed: dict = {
176+
"mac": mac,
177+
"message": message
178+
}
179+
with open(target_file, mode) as f:
180+
json.dump(unparsed, f)
181+
return not received
182+
except SyntaxError:
183+
raise
184+
185+
def receive_to_dict(self) -> dict:
186+
"""
187+
Unparses received `string` into a `dict` object
188+
189+
Args:
190+
191+
None:
192+
193+
Returns:
194+
195+
unparsed (dict): `dictionary` object containing unparsed equivalent of the received `.json`
196+
"""
197+
data: list | None = self.receive_message()
198+
if data == None: return {}
199+
mac: str = str(data[0])
200+
message = json.loads(str(data[-1]))
201+
unparsed: dict = {
202+
"mac": mac,
203+
"message": message
204+
}
205+
return unparsed

0 commit comments

Comments
 (0)