1 |
21e4cc2f
|
Martin Forejt
|
import logging
|
2 |
57cc3beb
|
Martin Forejt
|
import os
|
3 |
|
|
import time
|
4 |
|
|
|
5 |
|
|
from aswi2021vochomurka.model.Message import Message
|
6 |
|
|
from typing import TextIO
|
7 |
|
|
|
8 |
|
|
trans = str.maketrans({
|
9 |
|
|
"/": "_",
|
10 |
|
|
"\\": "_",
|
11 |
|
|
":": "_",
|
12 |
|
|
"\"": "_",
|
13 |
|
|
"$": "_",
|
14 |
|
|
"*": "_",
|
15 |
|
|
".": "_"})
|
16 |
|
|
|
17 |
|
|
|
18 |
64ca87d0
|
Martin Forejt
|
def create_filename(message: Message) -> str:
|
19 |
|
|
"""
|
20 |
|
|
Create file name based on message data
|
21 |
|
|
:param message: message
|
22 |
|
|
:return: filename
|
23 |
|
|
"""
|
24 |
57cc3beb
|
Martin Forejt
|
name = "data/" + message.topic.translate(trans) + "/" + message.date + "_" + message.time + ".csv"
|
25 |
|
|
return name
|
26 |
|
|
|
27 |
|
|
|
28 |
|
|
class FileManager:
|
29 |
64ca87d0
|
Martin Forejt
|
"""
|
30 |
|
|
Helper class for writing incoming message to files
|
31 |
|
|
Each topic has created own instance of this class
|
32 |
|
|
"""
|
33 |
57cc3beb
|
Martin Forejt
|
topic: str
|
34 |
|
|
lastUpdate: float
|
35 |
|
|
file: TextIO
|
36 |
|
|
|
37 |
|
|
def __init__(self, topic: str, message: Message):
|
38 |
64ca87d0
|
Martin Forejt
|
"""
|
39 |
|
|
Constructing new FileManager will create new file and write first message
|
40 |
|
|
:param topic: topic
|
41 |
|
|
:param message: message
|
42 |
|
|
:except when creating new file fails
|
43 |
|
|
"""
|
44 |
57cc3beb
|
Martin Forejt
|
self.topic = topic
|
45 |
21e4cc2f
|
Martin Forejt
|
logging.debug('opening file ' + self.topic)
|
46 |
57cc3beb
|
Martin Forejt
|
|
47 |
|
|
try:
|
48 |
|
|
filename = create_filename(message)
|
49 |
|
|
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
50 |
|
|
self.file = open(filename, "w+")
|
51 |
|
|
except Exception as error:
|
52 |
21e4cc2f
|
Martin Forejt
|
logging.warning(error)
|
53 |
57cc3beb
|
Martin Forejt
|
raise error
|
54 |
|
|
self.write(message)
|
55 |
|
|
|
56 |
|
|
def write(self, message: Message):
|
57 |
64ca87d0
|
Martin Forejt
|
"""
|
58 |
|
|
Append message to file
|
59 |
|
|
:param message: message
|
60 |
|
|
"""
|
61 |
57cc3beb
|
Martin Forejt
|
self.file.write(message.date + ";" + message.time + ";" + str(message.index) + ";" + str(message.value) + "\n")
|
62 |
|
|
self.lastUpdate = time.time()
|
63 |
|
|
|
64 |
|
|
def close(self):
|
65 |
64ca87d0
|
Martin Forejt
|
"""
|
66 |
|
|
Close file
|
67 |
|
|
"""
|
68 |
21e4cc2f
|
Martin Forejt
|
logging.debug('closing file ' + self.topic)
|
69 |
57cc3beb
|
Martin Forejt
|
self.file.flush()
|
70 |
|
|
self.file.close()
|