Added final touches

This commit is contained in:
Dmitriy Shishkov 2023-06-03 23:34:50 +03:00
parent 19330ef3dc
commit 27d8014f56
Signed by: dm1sh
GPG Key ID: 027994B0AA357688
4 changed files with 106 additions and 65 deletions

View File

@ -49,10 +49,10 @@
</rect> </rect>
</property> </property>
<property name="text"> <property name="text">
<string>GET URL</string> <string>POST URL</string>
</property> </property>
</widget> </widget>
<widget class="QLineEdit" name="lineEdit_URL"> <widget class="QLineEdit" name="lineEdit_POST_URL">
<property name="geometry"> <property name="geometry">
<rect> <rect>
<x>430</x> <x>430</x>
@ -75,7 +75,7 @@
<string>Журнал запросов</string> <string>Журнал запросов</string>
</property> </property>
</widget> </widget>
<widget class="QLCDNumber" name="lcd_temp"> <widget class="QLCDNumber" name="lcd_temperature">
<property name="geometry"> <property name="geometry">
<rect> <rect>
<x>550</x> <x>550</x>
@ -103,7 +103,6 @@
<property name="font"> <property name="font">
<font> <font>
<pointsize>8</pointsize> <pointsize>8</pointsize>
<weight>50</weight>
<bold>false</bold> <bold>false</bold>
</font> </font>
</property> </property>
@ -128,7 +127,6 @@
</property> </property>
<property name="font"> <property name="font">
<font> <font>
<weight>50</weight>
<bold>false</bold> <bold>false</bold>
</font> </font>
</property> </property>
@ -235,7 +233,7 @@
<string/> <string/>
</property> </property>
<property name="pixmap"> <property name="pixmap">
<pixmap resource="../res/Res.qrc">:/img/off.svg</pixmap> <pixmap resource="res/Res.qrc">:/img/off.svg</pixmap>
</property> </property>
<property name="scaledContents"> <property name="scaledContents">
<bool>true</bool> <bool>true</bool>
@ -254,7 +252,7 @@
<string/> <string/>
</property> </property>
<property name="pixmap"> <property name="pixmap">
<pixmap resource="../res/Res.qrc">:/img/ON.svg</pixmap> <pixmap resource="res/Res.qrc">:/img/ON.svg</pixmap>
</property> </property>
<property name="scaledContents"> <property name="scaledContents">
<bool>true</bool> <bool>true</bool>
@ -273,7 +271,7 @@
<string/> <string/>
</property> </property>
<property name="pixmap"> <property name="pixmap">
<pixmap resource="../res/Res.qrc">:/img/led_on.svg</pixmap> <pixmap resource="res/Res.qrc">:/img/led_on.svg</pixmap>
</property> </property>
<property name="scaledContents"> <property name="scaledContents">
<bool>true</bool> <bool>true</bool>
@ -295,7 +293,7 @@
<string/> <string/>
</property> </property>
<property name="pixmap"> <property name="pixmap">
<pixmap resource="../res/Res.qrc">:/img/led_off.svg</pixmap> <pixmap resource="res/Res.qrc">:/img/led_off.svg</pixmap>
</property> </property>
<property name="scaledContents"> <property name="scaledContents">
<bool>true</bool> <bool>true</bool>
@ -340,7 +338,7 @@
<string/> <string/>
</property> </property>
<property name="pixmap"> <property name="pixmap">
<pixmap resource="../res/Res.qrc">:/img/led_on.svg</pixmap> <pixmap resource="res/Res.qrc">:/img/led_on.svg</pixmap>
</property> </property>
<property name="scaledContents"> <property name="scaledContents">
<bool>true</bool> <bool>true</bool>
@ -359,7 +357,7 @@
<string/> <string/>
</property> </property>
<property name="pixmap"> <property name="pixmap">
<pixmap resource="../res/Res.qrc">:/img/led_off.svg</pixmap> <pixmap resource="res/Res.qrc">:/img/led_off.svg</pixmap>
</property> </property>
<property name="scaledContents"> <property name="scaledContents">
<bool>true</bool> <bool>true</bool>
@ -391,7 +389,7 @@
<string/> <string/>
</property> </property>
<property name="pixmap"> <property name="pixmap">
<pixmap resource="../res/Res.qrc">:/img/led_on.svg</pixmap> <pixmap resource="res/Res.qrc">:/img/led_on.svg</pixmap>
</property> </property>
<property name="scaledContents"> <property name="scaledContents">
<bool>true</bool> <bool>true</bool>
@ -410,7 +408,7 @@
<string/> <string/>
</property> </property>
<property name="pixmap"> <property name="pixmap">
<pixmap resource="../res/Res.qrc">:/img/led_off.svg</pixmap> <pixmap resource="res/Res.qrc">:/img/led_off.svg</pixmap>
</property> </property>
<property name="scaledContents"> <property name="scaledContents">
<bool>true</bool> <bool>true</bool>
@ -429,7 +427,7 @@
<string/> <string/>
</property> </property>
<property name="pixmap"> <property name="pixmap">
<pixmap resource="../res/Res.qrc">:/img/off.svg</pixmap> <pixmap resource="res/Res.qrc">:/img/off.svg</pixmap>
</property> </property>
<property name="scaledContents"> <property name="scaledContents">
<bool>true</bool> <bool>true</bool>
@ -448,7 +446,7 @@
<string/> <string/>
</property> </property>
<property name="pixmap"> <property name="pixmap">
<pixmap resource="../res/Res.qrc">:/img/ON.svg</pixmap> <pixmap resource="res/Res.qrc">:/img/ON.svg</pixmap>
</property> </property>
<property name="scaledContents"> <property name="scaledContents">
<bool>true</bool> <bool>true</bool>
@ -467,7 +465,7 @@
<string/> <string/>
</property> </property>
<property name="pixmap"> <property name="pixmap">
<pixmap resource="../res/Res.qrc">:/img/off.svg</pixmap> <pixmap resource="res/Res.qrc">:/img/off.svg</pixmap>
</property> </property>
<property name="scaledContents"> <property name="scaledContents">
<bool>true</bool> <bool>true</bool>
@ -486,7 +484,7 @@
<string/> <string/>
</property> </property>
<property name="pixmap"> <property name="pixmap">
<pixmap resource="../res/Res.qrc">:/img/ON.svg</pixmap> <pixmap resource="res/Res.qrc">:/img/ON.svg</pixmap>
</property> </property>
<property name="scaledContents"> <property name="scaledContents">
<bool>true</bool> <bool>true</bool>
@ -504,7 +502,6 @@
<property name="font"> <property name="font">
<font> <font>
<pointsize>8</pointsize> <pointsize>8</pointsize>
<weight>50</weight>
<bold>false</bold> <bold>false</bold>
</font> </font>
</property> </property>
@ -556,7 +553,6 @@
<property name="font"> <property name="font">
<font> <font>
<pointsize>8</pointsize> <pointsize>8</pointsize>
<weight>50</weight>
<bold>false</bold> <bold>false</bold>
</font> </font>
</property> </property>
@ -564,7 +560,7 @@
<string>Освещенность</string> <string>Освещенность</string>
</property> </property>
</widget> </widget>
<widget class="QLCDNumber" name="lcd_abient_light"> <widget class="QLCDNumber" name="lcd_ambient_light">
<property name="geometry"> <property name="geometry">
<rect> <rect>
<x>550</x> <x>550</x>
@ -592,7 +588,6 @@
<property name="font"> <property name="font">
<font> <font>
<pointsize>8</pointsize> <pointsize>8</pointsize>
<weight>50</weight>
<bold>false</bold> <bold>false</bold>
</font> </font>
</property> </property>
@ -612,7 +607,6 @@
<property name="font"> <property name="font">
<font> <font>
<pointsize>8</pointsize> <pointsize>8</pointsize>
<weight>50</weight>
<bold>false</bold> <bold>false</bold>
</font> </font>
</property> </property>
@ -847,7 +841,6 @@
</property> </property>
<property name="font"> <property name="font">
<font> <font>
<weight>50</weight>
<bold>false</bold> <bold>false</bold>
</font> </font>
</property> </property>
@ -896,7 +889,7 @@
<enum>QLCDNumber::Flat</enum> <enum>QLCDNumber::Flat</enum>
</property> </property>
</widget> </widget>
<widget class="QLabel" name="label_abient_light"> <widget class="QLabel" name="label_ambient_light">
<property name="geometry"> <property name="geometry">
<rect> <rect>
<x>310</x> <x>310</x>
@ -908,7 +901,6 @@
<property name="font"> <property name="font">
<font> <font>
<pointsize>8</pointsize> <pointsize>8</pointsize>
<weight>50</weight>
<bold>false</bold> <bold>false</bold>
</font> </font>
</property> </property>
@ -968,7 +960,6 @@
<font> <font>
<family>MS Shell Dlg 2</family> <family>MS Shell Dlg 2</family>
<pointsize>8</pointsize> <pointsize>8</pointsize>
<weight>50</weight>
<bold>false</bold> <bold>false</bold>
</font> </font>
</property> </property>
@ -999,7 +990,7 @@
<string>Отправить GET запрос</string> <string>Отправить GET запрос</string>
</property> </property>
</widget> </widget>
<widget class="QLineEdit" name="lineEdit_request"> <widget class="QLineEdit" name="lineEdit_GET_URL">
<property name="geometry"> <property name="geometry">
<rect> <rect>
<x>430</x> <x>430</x>
@ -1048,7 +1039,7 @@
</rect> </rect>
</property> </property>
<property name="text"> <property name="text">
<string>POST URL</string> <string>GET URL</string>
</property> </property>
</widget> </widget>
<widget class="QLabel" name="label_secends"> <widget class="QLabel" name="label_secends">
@ -1071,12 +1062,13 @@
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>1185</width> <width>1185</width>
<height>18</height> <height>28</height>
</rect> </rect>
</property> </property>
</widget> </widget>
</widget> </widget>
<resources> <resources>
<include location="res/Res.qrc"/>
<include location="../res/Res.qrc"/> <include location="../res/Res.qrc"/>
</resources> </resources>
<connections/> <connections/>

View File

@ -4,19 +4,22 @@
"defaultMDNSname": "localhost:3001", "defaultMDNSname": "localhost:3001",
"defaultPostRoute": "/postvalue", "defaultPostRoute": "/postvalue",
"defaultGetRoute": "/sensval", "defaultGetRoute": "/sensval",
"pressure": "355", "LED1": true,
"LED2": false,
"LED3": true,
"pressure": 355,
"temperature": [2, 45, 56, 66, 12, 30, 23, 25, 22, 15], "temperature": [2, 45, 56, 66, 12, 30, 23, 25, 22, 15],
"button1State": "True", "button1State": true,
"button2State": "False", "button2State": false,
"button3State": "True", "button3State": true,
"ambient_light": "1", "ambient_light": 1,
"red_light": "1", "red_light": 1,
"green_light":"1", "green_light": 1,
"blue_light":"0", "blue_light": 0,
"lightness": "0", "lightness": 0,
"acceleration_x": "12", "acceleration_x": 12,
"acceleration_y": "23", "acceleration_y": 23,
"acceleration_z": "11", "acceleration_z": 11,
"defaultRGBLeds": { "defaultRGBLeds": {
"leds1": {"red": 0, "green": 0, "blue": 0}, "leds1": {"red": 0, "green": 0, "blue": 0},
"leds2": {"red": 0, "green": 0, "blue": 0}, "leds2": {"red": 0, "green": 0, "blue": 0},
@ -27,5 +30,6 @@
"leds7": {"red": 0, "green": 0, "blue": 0}, "leds7": {"red": 0, "green": 0, "blue": 0},
"leds8": {"red": 0, "green": 0, "blue": 0} "leds8": {"red": 0, "green": 0, "blue": 0}
}, },
"defaultUpdateInterval": 5000 "defaultUpdateInterval": 5000,
"startWithAutoupdate": false
} }

82
main.py
View File

@ -55,20 +55,19 @@ class AppWindow(QMainWindow):
self.nam = QNetworkAccessManager() self.nam = QNetworkAccessManager()
# Init plotter # Init plotter
self.plot = Plot(self.ui.plotwidget) self.plot = Plot(self.ui.plotwidget, initial_array=conf["temperature"])
# Set window title # Set window title
self.setWindowTitle("Lr4") self.setWindowTitle("Lr4")
# Init request url editors # Init request url editors
self.ui.lineEdit_URL.setText("http://" + conf['defaultMDNSname'] + conf['defaultPostRoute']) self.ui.lineEdit_POST_URL.setText("http://" + conf['defaultMDNSname'] + conf['defaultPostRoute'])
self.ui.lineEdit_request.setText("http://" + conf['defaultMDNSname'] + conf['defaultGetRoute']) self.ui.lineEdit_GET_URL.setText("http://" + conf['defaultMDNSname'] + conf['defaultGetRoute'])
# Init LED controls # Init LED controls
for i in range(1, 4): for i in range(1, 4):
getattr(self.ui, f"pushButton_switch_lamp{i}").setCheckable(True) # вкл режим перекл getattr(self.ui, f"pushButton_switch_lamp{i}").setCheckable(True) # вкл режим перекл
getattr(self.ui, f"pushButton_switch_lamp{i}").setChecked(False) # нач значение self.handle_toggle_lamp(i, conf[f"LED{i}"])
getattr(self.ui, f"label_lamp_on{i}").hide()
getattr(self.ui, f"pushButton_switch_lamp{i}").toggled["bool"].connect(lambda val, i=i: self.handle_toggle_lamp(i, val)) getattr(self.ui, f"pushButton_switch_lamp{i}").toggled["bool"].connect(lambda val, i=i: self.handle_toggle_lamp(i, val))
# Setup request manual triggers # Setup request manual triggers
@ -81,8 +80,13 @@ class AppWindow(QMainWindow):
# Store RGB LEDs default values # Store RGB LEDs default values
self.rgb_leds_state = conf["defaultRGBLeds"] self.rgb_leds_state = conf["defaultRGBLeds"]
# Init RGB LEDs as turned off self.update_colors(self.rgb_leds_state)
self.switch_all(False)
self.update_buttons(self.convert_buttons_state(conf))
# Init LCDs values
self.update_lcds(conf)
self.ui.lcd_temperature.display(conf["temperature"][-1])
# Setup RGB LED stip click handlers # Setup RGB LED stip click handlers
for led in self.ui.led_array: for led in self.ui.led_array:
@ -107,6 +111,8 @@ class AppWindow(QMainWindow):
# Setup autoupdate toggler # Setup autoupdate toggler
self.ui.checkBox_autoupdate.stateChanged.connect(self.handle_toggle_autoupdate) self.ui.checkBox_autoupdate.stateChanged.connect(self.handle_toggle_autoupdate)
self.ui.checkBox_autoupdate.setChecked(conf["startWithAutoupdate"])
def handle_toggle_autoupdate(self): def handle_toggle_autoupdate(self):
""" """
@ -116,6 +122,8 @@ class AppWindow(QMainWindow):
if self.ui.checkBox_autoupdate.isChecked(): if self.ui.checkBox_autoupdate.isChecked():
interval_s = self.ui.spinBox_autoupdate.value() interval_s = self.ui.spinBox_autoupdate.value()
self.timer.start(interval_s * 1000) self.timer.start(interval_s * 1000)
self.timer.timeout.emit() # Trigger timer event immediately
else: else:
self.timer.stop() self.timer.stop()
@ -263,7 +271,7 @@ class AppWindow(QMainWindow):
""" """
# Get inputed url # Get inputed url
url = self.ui.lineEdit_URL.text() url = self.ui.lineEdit_POST_URL.text()
# compose body # compose body
json_data = self.compose_post_json_data() json_data = self.compose_post_json_data()
@ -291,7 +299,7 @@ class AppWindow(QMainWindow):
GET запрос GET запрос
""" """
url = self.ui.lineEdit_request.text() url = self.ui.lineEdit_GET_URL.text()
request = QNetworkRequest(QUrl(url)) request = QNetworkRequest(QUrl(url))
@ -319,9 +327,23 @@ class AppWindow(QMainWindow):
func(self) # calling actual handler func(self) # calling actual handler
elif err == QNetworkReply.NetworkError.OperationCanceledError: elif err == QNetworkReply.NetworkError.OperationCanceledError:
self.ui.textEdit_message.append(f"{operation} запрос был отменён, так как не успел выполниться до нового вызова") self.ui.textEdit_message.append(f"{operation} запрос был отменён, так как не успел выполниться до нового вызова")
elif err == QNetworkReply.NetworkError.TemporaryNetworkFailureError:
self.ui.textEdit_message.append(f"Произошла временная ошибка при {operation} запросе, повторите запрос ещё раз")
else: else:
status_code = reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute) msg = f"Ошибка при {operation} запросе: "
self.ui.textEdit_message.append(f'Ошибка при {operation} запросе: {status_code}') if (err == QNetworkReply.NetworkError.ConnectionRefusedError
or err == QNetworkReply.NetworkError.RemoteHostClosedError
or err == QNetworkReply.NetworkError.HostNotFoundError
or err == QNetworkReply.NetworkError.TimeoutError
or err == QNetworkReply.NetworkError.SslHandshakeFailedError
or err == QNetworkReply.NetworkError.NetworkSessionFailedError
or err == QNetworkReply.NetworkError.BackgroundRequestNotAllowedError
or err == QNetworkReply.NetworkError.TooManyRedirectsError
or err == QNetworkReply.NetworkError.InsecureRedirectError):
self.ui.textEdit_message.append(msg + 'не удалось установить подключение к серверу')
else:
status_code = reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute)
self.ui.textEdit_message.append(msg + f'сервер вернул статус код {status_code}')
return wrapper return wrapper
@ -347,23 +369,32 @@ class AppWindow(QMainWindow):
for i in range(1,4): for i in range(1,4):
self.handle_toggle_lamp(i, data[f"LED{i}"]) self.handle_toggle_lamp(i, data[f"LED{i}"])
# convert buttons self.update_buttons(self.convert_buttons_state(data))
# Update LCDs
self.update_lcds(data)
# Append dot to plot and set corresponding LCD
self.plot.update(data["temperature"])
self.ui.lcd_temperature.display(data["temperature"])
self.update_colors(data)
def convert_buttons_state(self, data: dict[str, bool]) -> list[bool]:
buttons_status = list() buttons_status = list()
for i in range(1, 4): for i in range(1, 4):
buttons_status.append(data[f"button{i}State"]) buttons_status.append(data[f"button{i}State"])
self.update_buttons(buttons_status) return buttons_status
# Update LCDs
color_l=("ambient_light", "red_light", "green_light", "blue_light", "lightness","acceleration_x", "acceleration_y", "acceleration_z", "pressure") def update_lcds(self, data: dict):
color_l=("ambient_light", "red_light", "green_light", "blue_light", "lightness", "acceleration_x", "acceleration_y", "acceleration_z", "pressure")
for s in color_l: for s in color_l:
getattr(self.ui, "lcd_" + s).display(data[s]) getattr(self.ui, "lcd_" + s).display(data[s])
# Append dot to plot
self.plot.update(data["temperature"])
def update_buttons(self, bs: list[bool]): def update_buttons(self, bs: list[bool]):
for i in range(1, 4): for i in range(1, 4):
button_on = bs[i-1] button_on = bs[i-1]
@ -379,6 +410,15 @@ class AppWindow(QMainWindow):
label_tumbler_off.show() label_tumbler_off.show()
def update_colors(self, new_state: dict[str, dict[int]]):
for name in self.rgb_leds_state.keys():
self.rgb_leds_state[name] = new_state[name]
self.paint_led_color(
getattr(self.ui, name),
QColor(*list(map(lambda c: new_state[name][c], RGB)))
)
if __name__ == "__main__": if __name__ == "__main__":
app = QApplication(sys.argv) app = QApplication(sys.argv)

View File

@ -10,8 +10,13 @@ class Plot():
QT bar plot drawing class QT bar plot drawing class
""" """
def __init__(self, widget, arr_len = 20, default_val = 20): def __init__(self, widget, arr_len = 20, default_val = 20, initial_array = []):
self.__arr_vals = [default_val] * arr_len # TODO: Инициализировать значениями из conf["temperature"] if initial_array:
self.__arr_vals = initial_array
arr_len = len(initial_array)
else:
self.__arr_vals = [default_val] * arr_len
self.__x = list(range(1, arr_len + 1)) self.__x = list(range(1, arr_len + 1))
self.__plot = pg.plot() #создает объект PlotWidget из библиотеки PyqtGraph self.__plot = pg.plot() #создает объект PlotWidget из библиотеки PyqtGraph