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

View File

@ -4,19 +4,22 @@
"defaultMDNSname": "localhost:3001",
"defaultPostRoute": "/postvalue",
"defaultGetRoute": "/sensval",
"pressure": "355",
"LED1": true,
"LED2": false,
"LED3": true,
"pressure": 355,
"temperature": [2, 45, 56, 66, 12, 30, 23, 25, 22, 15],
"button1State": "True",
"button2State": "False",
"button3State": "True",
"ambient_light": "1",
"red_light": "1",
"green_light":"1",
"blue_light":"0",
"lightness": "0",
"acceleration_x": "12",
"acceleration_y": "23",
"acceleration_z": "11",
"button1State": true,
"button2State": false,
"button3State": true,
"ambient_light": 1,
"red_light": 1,
"green_light": 1,
"blue_light": 0,
"lightness": 0,
"acceleration_x": 12,
"acceleration_y": 23,
"acceleration_z": 11,
"defaultRGBLeds": {
"leds1": {"red": 0, "green": 0, "blue": 0},
"leds2": {"red": 0, "green": 0, "blue": 0},
@ -27,5 +30,6 @@
"leds7": {"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()
# Init plotter
self.plot = Plot(self.ui.plotwidget)
self.plot = Plot(self.ui.plotwidget, initial_array=conf["temperature"])
# Set window title
self.setWindowTitle("Lr4")
# Init request url editors
self.ui.lineEdit_URL.setText("http://" + conf['defaultMDNSname'] + conf['defaultPostRoute'])
self.ui.lineEdit_request.setText("http://" + conf['defaultMDNSname'] + conf['defaultGetRoute'])
self.ui.lineEdit_POST_URL.setText("http://" + conf['defaultMDNSname'] + conf['defaultPostRoute'])
self.ui.lineEdit_GET_URL.setText("http://" + conf['defaultMDNSname'] + conf['defaultGetRoute'])
# Init LED controls
for i in range(1, 4):
getattr(self.ui, f"pushButton_switch_lamp{i}").setCheckable(True) # вкл режим перекл
getattr(self.ui, f"pushButton_switch_lamp{i}").setChecked(False) # нач значение
getattr(self.ui, f"label_lamp_on{i}").hide()
self.handle_toggle_lamp(i, conf[f"LED{i}"])
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
@ -81,8 +80,13 @@ class AppWindow(QMainWindow):
# Store RGB LEDs default values
self.rgb_leds_state = conf["defaultRGBLeds"]
# Init RGB LEDs as turned off
self.switch_all(False)
self.update_colors(self.rgb_leds_state)
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
for led in self.ui.led_array:
@ -107,6 +111,8 @@ class AppWindow(QMainWindow):
# Setup autoupdate toggler
self.ui.checkBox_autoupdate.stateChanged.connect(self.handle_toggle_autoupdate)
self.ui.checkBox_autoupdate.setChecked(conf["startWithAutoupdate"])
def handle_toggle_autoupdate(self):
"""
@ -116,6 +122,8 @@ class AppWindow(QMainWindow):
if self.ui.checkBox_autoupdate.isChecked():
interval_s = self.ui.spinBox_autoupdate.value()
self.timer.start(interval_s * 1000)
self.timer.timeout.emit() # Trigger timer event immediately
else:
self.timer.stop()
@ -263,7 +271,7 @@ class AppWindow(QMainWindow):
"""
# Get inputed url
url = self.ui.lineEdit_URL.text()
url = self.ui.lineEdit_POST_URL.text()
# compose body
json_data = self.compose_post_json_data()
@ -291,7 +299,7 @@ class AppWindow(QMainWindow):
GET запрос
"""
url = self.ui.lineEdit_request.text()
url = self.ui.lineEdit_GET_URL.text()
request = QNetworkRequest(QUrl(url))
@ -319,9 +327,23 @@ class AppWindow(QMainWindow):
func(self) # calling actual handler
elif err == QNetworkReply.NetworkError.OperationCanceledError:
self.ui.textEdit_message.append(f"{operation} запрос был отменён, так как не успел выполниться до нового вызова")
elif err == QNetworkReply.NetworkError.TemporaryNetworkFailureError:
self.ui.textEdit_message.append(f"Произошла временная ошибка при {operation} запросе, повторите запрос ещё раз")
else:
status_code = reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute)
self.ui.textEdit_message.append(f'Ошибка при {operation} запросе: {status_code}')
msg = f"Ошибка при {operation} запросе: "
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
@ -347,23 +369,32 @@ class AppWindow(QMainWindow):
for i in range(1,4):
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()
for i in range(1, 4):
buttons_status.append(data[f"button{i}State"])
self.update_buttons(buttons_status)
# Update LCDs
color_l=("ambient_light", "red_light", "green_light", "blue_light", "lightness","acceleration_x", "acceleration_y", "acceleration_z", "pressure")
return buttons_status
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:
getattr(self.ui, "lcd_" + s).display(data[s])
# Append dot to plot
self.plot.update(data["temperature"])
def update_buttons(self, bs: list[bool]):
for i in range(1, 4):
button_on = bs[i-1]
@ -379,6 +410,15 @@ class AppWindow(QMainWindow):
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__":
app = QApplication(sys.argv)

View File

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