Skip to content

Commit 60895ab

Browse files
committed
add:multi threading debug log
1 parent 65f8df5 commit 60895ab

File tree

8 files changed

+128
-25
lines changed

8 files changed

+128
-25
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ __pycache__
22
app/resource/images/*
33
dist/*
44
build/*
5+
log/*
6+
debug/*
57
*.xml
68
*.spec
79
*.ps1

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,9 @@ A simple and badly-written program to display basic information of your HUAWEI M
2727
- Current Day Duration
2828
- Data Limit
2929

30-
## Implementation
30+
## How it works
3131

32-
The program post http request to get information from the router and parse the result.
32+
The program posts http request to get information from the router and parse the result.
3333

3434
Currently, the program is unable to perform password authentication due to lack of knowledge on the detailed secure mechanism. Thus, it can only get some of the result that do not require such authentication.
3535

app/common/RouterInfo.py

Lines changed: 89 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33
import hashlib
44
import base64
55
import os
6-
6+
import concurrent.futures
77

88
from notifypy import Notify
99
from .config import cfg
10+
from.global_logger import logger
1011

1112
class Router_HW:
1213
def __init__(
@@ -15,6 +16,7 @@ def __init__(
1516
login_admin_password = "password",
1617
router_ip = "192.168.8.1"
1718
) -> None:
19+
os.makedirs('debug', exist_ok=True)
1820
os.environ['NO_PROXY'] = router_ip
1921
self.session_url = 'http://' + router_ip + '/api/webserver/SesTokInfo'
2022
self.status_url = 'http://' + router_ip + '/api/monitoring/status'
@@ -93,29 +95,56 @@ def get_session_token(self):
9395
self.SesInfo = root.find('SesInfo').text
9496
self.cookies['SessionID'] = self.SesInfo
9597

96-
admin_user_password_token = self.LOGIN_ADMIN_USER + self.LOGIN_ADMIN_PASSWORD_BASE64 + self.SesInfo
97-
admin_user_password_token_sha256_hash = hashlib.sha256(admin_user_password_token.encode()).hexdigest()
98-
self.admin_user_password_token_base64 = base64.b64encode(admin_user_password_token_sha256_hash.encode()).decode().rstrip('\n')
98+
# admin_user_password_token = self.LOGIN_ADMIN_USER + self.LOGIN_ADMIN_PASSWORD_BASE64 + self.SesInfo
99+
# admin_user_password_token_sha256_hash = hashlib.sha256(admin_user_password_token.encode()).hexdigest()
100+
# self.admin_user_password_token_base64 = base64.b64encode(admin_user_password_token_sha256_hash.encode()).decode().rstrip('\n')
99101
else:
100-
print("Request 'get_session_token' with status code:", response_session.status_code)
102+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
103+
executor.submit(self.write_error_log, "Request 'get_session_token' failed with status code:" + response_session.status_code)
104+
# if cfg.get(cfg.enableLogging):
105+
# logger.error("Request 'get_session_token' failed with status code:" + response_session.status_code)
101106

102107
except:
103-
pass
108+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
109+
executor.submit(self.write_error_log, "`get_session_token` failed to reach router at " + self.session_url)
110+
# if cfg.get(cfg.enableLogging):
111+
# logger.error("`get_session_token` failed to reach router at " + self.session_url)
112+
113+
def write_debug_xml(self, response, filename):
114+
if cfg.get(cfg.enableLogging):
115+
with open('debug/' + filename + '.xml', 'w') as f:
116+
f.write(response.text)
117+
118+
def write_error_log(self, error_message):
119+
if cfg.get(cfg.enableLogging):
120+
logger.error(error_message)
121+
122+
def write_warning_log(self, warning_message):
123+
if cfg.get(cfg.enableLogging):
124+
logger.warning(warning_message)
104125

105126
def get_status(self):
106127
self.get_session_token()
107128
try:
108129
response_status = requests.get(self.status_url, headers=self.headers, timeout=60, verify=False, cookies=self.cookies)
109130
if response_status.status_code == 200:
110-
# with open('status.xml', 'w') as f:
111-
# f.write(response_status.text)
131+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
132+
executor.submit(self.write_debug_xml, response_status, "status")
133+
# if cfg.get(cfg.enableLogging):
134+
# with open('debug/status.xml', 'w') as f:
135+
# f.write(response_status.text)
112136
root = ET.fromstring(response_status.text)
113137

114-
# for key in root.iter():
115-
# print(key.tag, key.text)
116-
self.BatteryStatus = root.find('BatteryStatus').text
117-
self.BatteryStatusStr = "Charging" if self.BatteryStatus == "1" else "Not Charging"
118-
self.BatteryPercent = int(root.find('BatteryPercent').text)
138+
try:
139+
self.BatteryStatus = root.find('BatteryStatus').text
140+
self.BatteryStatusStr = "Charging" if self.BatteryStatus == "1" else "Not Charging"
141+
self.BatteryPercent = int(root.find('BatteryPercent').text)
142+
except:
143+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
144+
executor.submit(self.write_warning_log, "`get_status` failed to find battery information")
145+
# logger.warning("`get_status` failed to find battery information")
146+
self.BatteryStatusStr = "No battery"
147+
self.BatteryPercent = 100
119148

120149
sim_lock_status = int(root.find('simlockStatus').text)
121150
wifi_connection_status = int(root.find('WifiConnectionStatus').text)
@@ -233,11 +262,21 @@ def get_status(self):
233262
self.get_month_statistics()
234263
self.get_start_date()
235264

236-
self.month_statistics_dic["Month Percentage"] = round(self.monitoring_status_dic["Current Upload Download Raw"] / self.monitoring_status_dic["Traffic Max Limit Raw"] * 100, 2)
265+
if self.monitoring_status_dic["Traffic Max Limit Raw"] != 0:
266+
self.month_statistics_dic["Month Percentage"] = round(self.monitoring_status_dic["Current Upload Download Raw"] / self.monitoring_status_dic["Traffic Max Limit Raw"] * 100, 2)
267+
else:
268+
self.month_statistics_dic["Month Percentage"] = 0
237269

238270
else:
239-
print("Request 'get_status' failed with status code:", response_status.status_code)
271+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
272+
executor.submit(self.write_error_log, "Request 'get_status' failed with status code:" + response_status.status_code)
273+
# if cfg.get(cfg.enableLogging):
274+
# logger.error("Request 'get_status' failed with status code:" + response_status.status_code)
240275
except:
276+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
277+
executor.submit(self.write_error_log, "Request 'get_status' failed to reach router at " + self.session_url)
278+
# if cfg.get(cfg.enableLogging):
279+
# logger.error("`get_status` failed to reach router at " + self.session_url)
241280
self.monitoring_status_dic["Battery Percent"] = 0
242281
self.monitoring_status_dic["Sim Lock Status"] = "-"
243282
self.monitoring_status_dic["Wifi Connection Status"] = "-"
@@ -254,16 +293,22 @@ def get_status(self):
254293
self.traffic_statistics_dic["Signal Strength"] = 0
255294
self.traffic_statistics_dic["Network Type"] = "Device offline"
256295

257-
self.month_statistics_dic["Month Percentage"] = 0
296+
if self.monitoring_status_dic["Traffic Max Limit Raw"] != 0:
297+
self.month_statistics_dic["Month Percentage"] = round(self.monitoring_status_dic["Current Upload Download Raw"] / self.monitoring_status_dic["Traffic Max Limit Raw"] * 100, 2)
298+
else:
299+
self.month_statistics_dic["Month Percentage"] = 0
258300
pass
259301

260302
def get_traffic_statistics(self):
261303
self.get_session_token()
262304
try:
263305
response_status = requests.get(self.traffic_statistics_url, headers=self.headers, timeout=60, verify=False, cookies=self.cookies)
264306
if response_status.status_code == 200:
265-
# with open('traffic_statistics.xml', 'w') as f:
266-
# f.write(response_status.text)
307+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
308+
executor.submit(self.write_debug_xml, response_status, "traffic_statistics")
309+
# if cfg.get(cfg.enableLogging):
310+
# with open('debug/traffic_statistics.xml', 'w') as f:
311+
# f.write(response_status.text)
267312
root = ET.fromstring(response_status.text)
268313

269314
current_connect_time = self.calc_time(root.find('CurrentConnectTime').text)
@@ -280,8 +325,15 @@ def get_traffic_statistics(self):
280325
self.traffic_statistics_dic["Current Connect Time"] = current_connect_time
281326
self.traffic_statistics_dic["Total Connect Time"] = total_connect_time
282327
else:
283-
print("Request 'get_traffic_statistics' failed with status code:", response_status.status_code)
328+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
329+
executor.submit(self.write_error_log, "Request 'get_traffic_statistics' failed with status code:" + response_status.status_code)
330+
# if cfg.get(cfg.enableLogging):
331+
# logger.error("Request 'get_traffic_statistics' failed with status code:" + response_status.status_code)
284332
except:
333+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
334+
executor.submit(self.write_error_log, "Request 'get_traffic_statistics' failed to reach router at " + self.session_url)
335+
# if cfg.get(cfg.enableLogging):
336+
# logger.error("`get_traffic_statistics` failed to reach router at " + self.session_url)
285337
self.traffic_statistics_dic["Current Download Rate"] = "-"
286338
self.traffic_statistics_dic["Current Upload Rate"] = "-"
287339
self.traffic_statistics_dic["Total Upload"] = "-"
@@ -296,8 +348,11 @@ def get_month_statistics(self):
296348
self.month_statistics_url, headers=self.headers, timeout=60, verify=False, cookies=self.cookies
297349
)
298350
if response_status.status_code == 200:
299-
# with open('month_statistics.xml', 'w') as f:
300-
# f.write(response_status.text)
351+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
352+
executor.submit(self.write_debug_xml, response_status, "month_statistics")
353+
# if cfg.get(cfg.enableLogging):
354+
# with open('debug/month_statistics.xml', 'w') as f:
355+
# f.write(response_status.text)
301356
root = ET.fromstring(response_status.text)
302357

303358
current_month_download = self.calc_traffic(root.find('CurrentMonthDownload').text)
@@ -318,6 +373,10 @@ def get_month_statistics(self):
318373
self.monitoring_status_dic["Current Day Used"] = current_day_used
319374
self.monitoring_status_dic["Current Day Duration"] = current_day_duration
320375
except:
376+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
377+
executor.submit(self.write_error_log, "Request 'get_month_statistics' failed to reach router at " + self.session_url)
378+
# if cfg.get(cfg.enableLogging):
379+
# logger.error("`get_month_statistics` failed to reach router at " + self.session_url)
321380
self.monitoring_status_dic["Current Month Download"] = "-"
322381
self.monitoring_status_dic["Current Month Upload"] = "-"
323382
self.monitoring_status_dic["Current Upload Download Raw"] = 0
@@ -334,8 +393,11 @@ def get_start_date(self):
334393
self.start_date_url, headers=self.headers, timeout=60, verify=False, cookies=self.cookies
335394
)
336395
if response_status.status_code == 200:
337-
# with open('start_date.xml', 'w') as f:
338-
# f.write(response_status.text)
396+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
397+
executor.submit(self.write_debug_xml, response_status, "start_date")
398+
# if cfg.get(cfg.enableLogging):
399+
# with open('debug/start_date.xml', 'w') as f:
400+
# f.write(response_status.text)
339401
root = ET.fromstring(response_status.text)
340402

341403
data_limit = root.find('DataLimit').text
@@ -347,6 +409,10 @@ def get_start_date(self):
347409
self.monitoring_status_dic["Traffic Max Limit Raw"] = traffic_max_limit_raw
348410
self.month_statistics_dic["Current Upload Download"] = self.calc_traffic(self.monitoring_status_dic["Traffic Max Limit Raw"] - self.monitoring_status_dic["Current Upload Download Raw"])
349411
except:
412+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
413+
executor.submit(self.write_error_log, "Request 'get_start_date' failed to reach router at " + self.session_url)
414+
# if cfg.get(cfg.enableLogging):
415+
# logger.error("`get_start_date` failed to reach router at " + self.session_url)
350416
self.monitoring_status_dic["Data Limit"] = "-"
351417
self.month_statistics_dic["Traffic Max Limit"] = "-"
352418
self.monitoring_status_dic["Traffic Max Limit Raw"] = 0

app/common/config.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ class Config(QConfig):
5555

5656
batteryLowerBoundThreshold = RangeConfigItem("Battery", "batteryLowerBoundThreshold", 30, RangeValidator(0, 100))
5757

58+
enableLogging = ConfigItem("Developer", "enableLogging", False, BoolValidator())
5859

5960
YEAR = 2023
6061
AUTHOR = "ladbaby"

app/common/global_logger.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import logging
2+
import logging.handlers as handlers
3+
import time
4+
import os
5+
6+
logger = logging.getLogger('global')
7+
logger.setLevel(logging.DEBUG)
8+
9+
os.makedirs('log', exist_ok=True)
10+
11+
logHandler = handlers.RotatingFileHandler('log/debug.log', maxBytes=5242880, backupCount=2, encoding='utf-8')
12+
logHandler.setLevel(logging.DEBUG)
13+
formatter = logging.Formatter('%(asctime)s|%(levelname)s:%(message)s')
14+
logHandler.setFormatter(formatter)
15+
logger.addHandler(logHandler)

app/config/config.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@
1919
"DpiScale": "Auto",
2020
"Language": "en_US"
2121
},
22+
"Developer": {
23+
"enableLogging": false
24+
},
2225
"QFluentWidgets": {
2326
"ThemeColor": "#ff009faa",
2427
"ThemeMode": "Dark"

app/view/setting_interface.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,16 @@ def __init__(self, parent=None):
144144
parent=self.updateSoftwareGroup
145145
)
146146

147+
# developer
148+
self.developerGroup = SettingCardGroup(self.tr('Developer'), self.scrollWidget)
149+
self.enableLoggingCard = SwitchSettingCard(
150+
FIF.CODE,
151+
self.tr('Enable logging'),
152+
self.tr('log debug information'),
153+
configItem=cfg.enableLogging,
154+
parent=self.developerGroup
155+
)
156+
147157
# application
148158
self.aboutGroup = SettingCardGroup(self.tr('About'), self.scrollWidget)
149159
self.helpCard = HyperlinkCard(
@@ -215,6 +225,8 @@ def __initLayout(self):
215225
self.aboutGroup.addSettingCard(self.feedbackCard)
216226
self.aboutGroup.addSettingCard(self.aboutCard)
217227

228+
self.developerGroup.addSettingCard(self.enableLoggingCard)
229+
218230
# add setting card group to layout
219231
self.expandLayout.setSpacing(28)
220232
self.expandLayout.setContentsMargins(36, 10, 36, 0)
@@ -223,6 +235,7 @@ def __initLayout(self):
223235
self.expandLayout.addWidget(self.personalGroup)
224236
self.expandLayout.addWidget(self.materialGroup)
225237
self.expandLayout.addWidget(self.updateSoftwareGroup)
238+
self.expandLayout.addWidget(self.developerGroup)
226239
self.expandLayout.addWidget(self.aboutGroup)
227240

228241
def __showRestartTooltip(self):

main.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,13 @@
1212

1313
from app.common.config import cfg
1414
from app.view.main_window import MainWindow
15+
from app.common.global_logger import logger
1516

1617

1718

1819
if __name__ == "__main__":
20+
if cfg.get(cfg.enableLogging):
21+
logger.info("---HUAWEI Router Assistant started---")
1922
if cfg.get(cfg.dpiScale) == "Auto":
2023
QApplication.setHighDpiScaleFactorRoundingPolicy(
2124
Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)

0 commit comments

Comments
 (0)