Revize 4dc54176
Přidáno uživatelem Martin Forejt před téměř 4 roky(ů)
aswi2021vochomurka/view/main_view.py | ||
---|---|---|
1 |
from PyQt5.QtCore import QSize |
|
1 |
from PyQt5.QtCore import QSize, QObject, pyqtSignal, QThread
|
|
2 | 2 |
from PyQt5.QtWidgets import QMainWindow, QPlainTextEdit |
3 |
import paho.mqtt.client as mqtt |
|
4 |
|
|
5 |
|
|
6 |
class Worker(QObject): |
|
7 |
connected = pyqtSignal() |
|
8 |
newMessage = pyqtSignal(str) |
|
9 |
|
|
10 |
def on_connect(self, client, userdata, flags, rc, properties=None): |
|
11 |
print("Connected with result code " + str(rc)) |
|
12 |
self.connected.emit() |
|
13 |
# Subscribing in on_connect() means that if we lose the connection and |
|
14 |
# reconnect then subscriptions will be renewed. |
|
15 |
client.subscribe("#") |
|
16 |
|
|
17 |
# The callback for when a PUBLISH message is received from the server. |
|
18 |
def on_message(self, client, userdata, message): |
|
19 |
print(message.topic + " " + str(message.payload.decode("utf-8"))) |
|
20 |
self.newMessage.emit(message.topic + " " + str(message.payload.decode("utf-8"))) |
|
21 |
|
|
22 |
def start(self): |
|
23 |
client = mqtt.Client() |
|
24 |
client.on_connect = self.on_connect |
|
25 |
client.on_message = self.on_message |
|
26 |
|
|
27 |
client.connect("localhost", 1883, 60) |
|
28 |
|
|
29 |
# Blocking call that processes network traffic, dispatches callbacks and |
|
30 |
# handles reconnecting. |
|
31 |
# Other loop*() functions are available that give a threaded interface and a |
|
32 |
# manual interface. |
|
33 |
client.loop_forever() |
|
3 | 34 |
|
4 | 35 |
|
5 | 36 |
class MainView(QMainWindow): |
... | ... | |
15 | 46 |
self.b.insertPlainText("App started...\n") |
16 | 47 |
self.b.move(10, 10) |
17 | 48 |
self.b.resize(400, 200) |
49 |
|
|
50 |
self.thread = QThread() |
|
51 |
self.worker = Worker() |
|
52 |
self.worker.moveToThread(self.thread) |
|
53 |
self.thread.started.connect(self.worker.start) |
|
54 |
self.worker.newMessage.connect( |
|
55 |
lambda message: self.b.insertPlainText(message + "\n") |
|
56 |
) |
|
57 |
|
|
58 |
self.thread.start() |
Také k dispozici: Unified diff
Re #8489 - wip connect subscriber with window