Revize 21e4cc2f
Přidáno uživatelem Martin Forejt před téměř 4 roky(ů)
aswi2021vochomurka/app.py | ||
---|---|---|
1 |
import logging |
|
2 | ||
1 | 3 |
from PyQt5.QtWidgets import QApplication |
2 | 4 | |
3 | 5 |
from aswi2021vochomurka.view.main_view import MainView |
... | ... | |
5 | 7 | |
6 | 8 |
class Application(QApplication): |
7 | 9 |
def __init__(self, sys_argv): |
10 |
init_logger() |
|
8 | 11 |
super(Application, self).__init__(sys_argv) |
12 |
logging.info('App started') |
|
9 | 13 |
self.main_view = MainView() |
10 | 14 |
self.main_view.show() |
15 | ||
16 | ||
17 |
def init_logger(): |
|
18 |
logging.basicConfig( |
|
19 |
level=logging.DEBUG, |
|
20 |
filename='data/app.log', |
|
21 |
format='%(asctime)s %(name)s: %(levelname)-8s %(message)s', |
|
22 |
datefmt='%y-%m-%d %H:%M', |
|
23 |
filemode='w+' |
|
24 |
) |
|
25 | ||
26 |
formatter = logging.Formatter('%(asctime)s %(name)s: %(levelname)-8s %(message)s') |
|
27 |
console = logging.StreamHandler() |
|
28 |
console.setFormatter(formatter) |
|
29 |
console.setLevel(logging.INFO) |
|
30 |
logging.getLogger('').addHandler(console) |
|
31 | ||
32 |
logging.getLogger('apscheduler').setLevel(logging.WARNING) |
|
33 |
logging.getLogger('matplotlib').setLevel(logging.WARNING) |
aswi2021vochomurka/main.py | ||
---|---|---|
4 | 4 | |
5 | 5 | |
6 | 6 |
def start(): |
7 |
print("hello world Vochomurka") |
|
8 | 7 |
app = Application(sys.argv) |
9 | 8 |
sys.exit(app.exec_()) |
10 | 9 |
aswi2021vochomurka/model/Message.py | ||
---|---|---|
7 | 7 |
date: str |
8 | 8 |
time: str |
9 | 9 |
value: float |
10 | ||
11 |
def __str__(self) -> str: |
|
12 |
return 'topic=' + self.topic + ', datetime=' + self.date + 'T' + self.time + ', index=' + str( |
|
13 |
self.index) + ', value=' + str(self.value) |
aswi2021vochomurka/service/file_manager.py | ||
---|---|---|
1 |
import logging |
|
1 | 2 |
import os |
2 | 3 |
import time |
3 | 4 | |
... | ... | |
26 | 27 | |
27 | 28 |
def __init__(self, topic: str, message: Message): |
28 | 29 |
self.topic = topic |
30 |
logging.debug('opening file ' + self.topic) |
|
29 | 31 | |
30 | 32 |
try: |
31 | 33 |
filename = create_filename(message) |
32 | 34 |
os.makedirs(os.path.dirname(filename), exist_ok=True) |
33 | 35 |
self.file = open(filename, "w+") |
34 | 36 |
except Exception as error: |
35 |
print(error)
|
|
37 |
logging.warning(error)
|
|
36 | 38 |
raise error |
37 | 39 |
self.write(message) |
38 | 40 | |
... | ... | |
41 | 43 |
self.lastUpdate = time.time() |
42 | 44 | |
43 | 45 |
def close(self): |
46 |
logging.debug('closing file ' + self.topic) |
|
44 | 47 |
self.file.flush() |
45 | 48 |
self.file.close() |
aswi2021vochomurka/service/message_parser.py | ||
---|---|---|
1 |
import logging |
|
2 | ||
1 | 3 |
from paho.mqtt.client import MQTTMessage |
2 | 4 | |
3 | 5 |
from aswi2021vochomurka.model.Message import Message |
... | ... | |
10 | 12 |
def parse_mqtt_message(message: MQTTMessage) -> Message: |
11 | 13 |
data = message.payload.decode("utf-8") |
12 | 14 |
parts = data.split(";") |
15 |
logging.debug('Parsing message: ' + data + ', parts: ' + str(len(parts))) |
|
13 | 16 |
if len(parts) != 4: |
14 | 17 |
raise ParseException |
15 | 18 |
aswi2021vochomurka/service/mqtt/mqtt_subscriber.py | ||
---|---|---|
1 |
import logging |
|
2 | ||
1 | 3 |
import paho.mqtt.client as mqtt |
2 | 4 | |
3 | 5 |
from aswi2021vochomurka.service.message_parser import parse_mqtt_message, ParseException |
... | ... | |
8 | 10 | |
9 | 11 |
# The callback for when the client receives a CONNACK response from the server. |
10 | 12 |
def on_connect(self, client, userdata, flags, rc, properties=None): |
11 |
print("Connected with result code " + str(rc))
|
|
13 |
logging.info('Connected with result code ' + str(rc))
|
|
12 | 14 |
self.callback.onConnected() |
13 | 15 | |
14 | 16 |
# Subscribing in on_connect() means that if we lose the connection and |
15 | 17 |
# reconnect then subscriptions will be renewed. |
16 | 18 |
for topic in self.params.topics: |
17 |
print("Subscribed to topic: " + topic)
|
|
19 |
logging.info('Subscribed to topic: ' + topic)
|
|
18 | 20 |
client.subscribe(topic) |
19 | 21 | |
20 | 22 |
# The callback for when a PUBLISH message is received from the server. |
21 | 23 |
def on_message(self, client, userdata, message: mqtt.MQTTMessage): |
22 | 24 |
try: |
23 | 25 |
m = parse_mqtt_message(message) |
24 |
print(m)
|
|
26 |
logging.info('Message: ' + str(m))
|
|
25 | 27 |
self.callback.onMessage(m) |
26 | 28 |
self.write_to_file(m) |
27 | 29 |
except ParseException as error: |
28 |
print('invalid message data format') |
|
30 |
logging.warning('Invalid message data format of: ' + message.payload.decode('utf-8')) |
|
31 |
logging.info('Unsubscribed topic: ' + message.topic) |
|
29 | 32 |
client.unsubscribe(message.topic) |
30 |
# TODO better reaction on bad format |
|
31 | 33 |
pass |
32 | 34 | |
33 | 35 |
def on_disconnect(self, client, userdata, rc): |
36 |
logging.info('Disconnected') |
|
34 | 37 |
self.callback.onDisconnected() |
35 | 38 |
self.stop() |
36 | 39 | |
... | ... | |
40 | 43 |
client.on_connect = self.on_connect |
41 | 44 |
client.on_message = self.on_message |
42 | 45 |
client.on_disconnect = self.on_disconnect |
46 |
logging.info('Setting up client') |
|
43 | 47 | |
44 | 48 |
if not self.params.anonymous: |
49 |
logging.info('Using credentials, username=' + self.params.username + ', password=' + self.params.password) |
|
45 | 50 |
client.tls_set() |
46 | 51 |
client.username_pw_set(self.params.username, self.params.password) |
47 | 52 | |
48 | 53 |
try: |
54 |
logging.info('Connecting to: ' + self.params.connection.host + ':' + str(self.params.connection.port)) |
|
49 | 55 |
client.connect( |
50 | 56 |
self.params.connection.host, |
51 | 57 |
self.params.connection.port, |
52 | 58 |
self.params.connection.timeout |
53 | 59 |
) |
54 | 60 |
except Exception as error: |
61 |
logging.warning('Cannot connect') |
|
55 | 62 |
self.callback.onError() |
56 | 63 |
return |
57 | 64 |
aswi2021vochomurka/view/logger_view.py | ||
---|---|---|
1 |
import logging |
|
2 | ||
3 |
from PyQt5.QtCore import pyqtSignal, QObject |
|
4 |
from PyQt5.QtWidgets import QPlainTextEdit |
|
5 | ||
6 | ||
7 |
class LoggerView(logging.Handler, QObject): |
|
8 |
append = pyqtSignal(str) |
|
9 | ||
10 |
def __init__(self, parent): |
|
11 |
super().__init__() |
|
12 |
super(QObject, self).__init__() |
|
13 | ||
14 |
self.widget = QPlainTextEdit(parent) |
|
15 |
self.widget.setReadOnly(True) |
|
16 |
self.widget.setFixedHeight(120) |
|
17 |
self.append.connect( |
|
18 |
lambda msg: self.appendMessage(msg) |
|
19 |
) |
|
20 | ||
21 |
def emit(self, record): |
|
22 |
msg = self.format(record) |
|
23 |
self.append.emit(msg) |
|
24 | ||
25 |
def appendMessage(self, msg): |
|
26 |
self.widget.appendPlainText(msg) |
|
27 |
self.widget.verticalScrollBar().setValue(self.widget.verticalScrollBar().maximum()) |
|
28 | ||
29 |
def write(self, m): |
|
30 |
pass |
aswi2021vochomurka/view/main_view.py | ||
---|---|---|
1 |
import logging |
|
1 | 2 |
import math |
2 | 3 |
import random |
3 | 4 | |
... | ... | |
23 | 24 |
import matplotlib.pyplot as plt |
24 | 25 |
import random |
25 | 26 | |
27 |
from aswi2021vochomurka.view.logger_view import LoggerView |
|
28 | ||
26 | 29 | |
27 | 30 |
class Worker(QObject, SubscriberCallback): |
28 | 31 |
connected = pyqtSignal() |
... | ... | |
80 | 83 |
self.setMinimumSize(QSize(440, 240)) |
81 | 84 |
self.setWindowTitle("MQTT demo") |
82 | 85 | |
83 |
self.b = QPlainTextEdit(self) |
|
84 |
self.b.insertPlainText("App started...\n") |
|
86 |
# Add logger text field |
|
87 |
logger = LoggerView(self) |
|
88 |
formatter = logging.Formatter('%(asctime)s %(message)s', '%H:%M') |
|
89 |
logger.setFormatter(formatter) |
|
90 |
logger.setLevel(logging.INFO) |
|
91 |
logging.getLogger('').addHandler(logger) |
|
85 | 92 | |
86 | 93 |
layout = QVBoxLayout() |
87 |
layout.addWidget(self.b)
|
|
94 |
layout.addWidget(logger.widget)
|
|
88 | 95 |
layout.addWidget(self.toolbar) |
89 | 96 |
layout.addWidget(self.canvas) |
90 | 97 | |
... | ... | |
116 | 123 |
self.worker = Worker() |
117 | 124 |
self.worker.moveToThread(self.workerThread) |
118 | 125 |
self.workerThread.started.connect(self.worker.start) |
119 |
self.worker.newMessage.connect( |
|
120 |
lambda message: self.b.insertPlainText(message + "\n") |
|
121 |
) |
|
126 |
# self.worker.newMessage.connect(
|
|
127 |
# lambda message: self.b.insertPlainText(message + "\n")
|
|
128 |
# )
|
|
122 | 129 |
self.worker.window = self |
123 | 130 |
self.workerThread.start() |
Také k dispozici: Unified diff
Feature/8893 loggin to file