diff --git a/.gitignore b/.gitignore index b1e0a762..8cc108ef 100644 --- a/.gitignore +++ b/.gitignore @@ -2,8 +2,8 @@ /log/ /screenshot/ /maptile/* -/course/ridewithgps/* -/course/*html* +/courses/ridewithgps/* +/courses/*html* /.idea/ /.vscode/ /.venv/ diff --git a/course/.gitkeep b/courses/.gitkeep similarity index 100% rename from course/.gitkeep rename to courses/.gitkeep diff --git a/course/ridewithgps/.gitkeep b/courses/ridewithgps/.gitkeep similarity index 100% rename from course/ridewithgps/.gitkeep rename to courses/ridewithgps/.gitkeep diff --git a/modules/button_config.py b/modules/button_config.py index 8cae77c0..353cace9 100644 --- a/modules/button_config.py +++ b/modules/button_config.py @@ -160,7 +160,7 @@ def __init__(self, config): self.config = config def press_button(self, button_hard, press_button, index): - if self.config.gui == None or self.config.gui.stack_widget == None: + if self.config.gui is None or self.config.gui.stack_widget is None: return w_index = self.config.gui.stack_widget.currentIndex() diff --git a/modules/config.py b/modules/config.py index 17256df3..96ab2329 100644 --- a/modules/config.py +++ b/modules/config.py @@ -23,7 +23,7 @@ GPIO.setmode(GPIO.BCM) _IS_RASPI = True -except: +except ImportError: pass from modules.helper.setting import Setting @@ -52,7 +52,7 @@ class Config: G_AVERAGE_INCLUDING_ZERO = {"cadence": False, "power": True} # log several altitudes (from DEM and course file) - G_LOG_ALTITUDE_FROM_DATA_SOUCE = False + G_LOG_ALTITUDE_FROM_DATA_SOURCE = False # calculate index on course G_COURSE_INDEXING = True @@ -79,7 +79,7 @@ class Config: G_UNIT_HARDWARE = "" # install_dir - G_INSTALL_PATH = os.path.expanduser("~") + "/pizero_bikecomputer/" + G_INSTALL_PATH = os.path.join(os.path.expanduser("~"), "pizero_bikecomputer") # layout def G_LAYOUT_FILE = "layout.yaml" @@ -90,19 +90,17 @@ class Config: G_FONT_FULLPATH = "" G_FONT_NAME = "" - # course file - G_COURSE_DIR = "course/" - G_COURSE_FILE = "course.tcx" - G_COURSE_FILE_PATH = G_COURSE_DIR + G_COURSE_FILE - # G_CUESHEET_FILE = "course/cue_sheet.csv" + # courses + G_COURSE_DIR = "courses" + G_COURSE_FILE_PATH = os.path.join(G_COURSE_DIR, "course.tcx") G_CUESHEET_DISPLAY_NUM = 3 # max: 5 G_CUESHEET_SCROLL = False G_OBEXD_CMD = "/usr/libexec/bluetooth/obexd" G_RECEIVE_COURSE_FILE = "bluetooth_content_share.html" # log setting - G_LOG_DIR = "log/" - G_LOG_DB = G_LOG_DIR + "log.db" + G_LOG_DIR = "log" + G_LOG_DB = os.path.join(G_LOG_DIR, "log.db") G_LOG_START_DATE = None # asyncio semaphore @@ -320,7 +318,7 @@ class Config: G_DEM_MAP = "jpn_kokudo_chiri_in_DEM5A" # screenshot dir - G_SCREENSHOT_DIR = "screenshot/" + G_SCREENSHOT_DIR = "screenshots" # debug switch (change with --debug option) G_IS_DEBUG = False @@ -486,8 +484,6 @@ class Config: # GUI mode G_GUI_MODE = "PyQt" - # G_GUI_MODE = "QML" - # G_GUI_MODE = "Kivy" # PerformanceGraph: # 1st: POWER @@ -598,7 +594,7 @@ class Config: "USER_ROUTES_START": 0, "USER_ROUTES_OFFSET": 10, "URL_ROUTE_BASE_URL": "https://ridewithgps.com/routes/{route_id}", - "URL_ROUTE_DOWNLOAD_DIR": "./course/ridewithgps/", + "URL_ROUTE_DOWNLOAD_DIR": "./courses/ridewithgps/", "URL_UPLOAD": "https://ridewithgps.com/trips.json", "PARAMS": { "apikey": None, @@ -713,25 +709,29 @@ def __init__(self): # set dir if self.G_IS_RASPI: - self.G_SCREENSHOT_DIR = self.G_INSTALL_PATH + self.G_SCREENSHOT_DIR - self.G_LOG_DIR = self.G_INSTALL_PATH + self.G_LOG_DIR - self.G_LOG_DB = self.G_INSTALL_PATH + self.G_LOG_DB - self.G_LAYOUT_FILE = self.G_INSTALL_PATH + self.G_LAYOUT_FILE - self.G_COURSE_DIR = self.G_INSTALL_PATH + self.G_COURSE_DIR - self.G_COURSE_FILE_PATH = self.G_INSTALL_PATH + self.G_COURSE_FILE_PATH + self.G_SCREENSHOT_DIR = os.path.join( + self.G_INSTALL_PATH, self.G_SCREENSHOT_DIR + ) + self.G_LOG_DIR = os.path.join(self.G_INSTALL_PATH, self.G_LOG_DIR) + self.G_LOG_DB = os.path.join(self.G_INSTALL_PATH, self.G_LOG_DB) + self.G_LAYOUT_FILE = os.path.join(self.G_INSTALL_PATH, self.G_LAYOUT_FILE) + self.G_COURSE_DIR = os.path.join(self.G_INSTALL_PATH, self.G_COURSE_DIR) + self.G_COURSE_FILE_PATH = os.path.join( + self.G_INSTALL_PATH, self.G_COURSE_FILE_PATH + ) # layout file if not os.path.exists(self.G_LAYOUT_FILE): + default_layout_file = os.path.join("layouts", "layout-cycling.yaml") if self.G_IS_RASPI: - shutil.copy( - self.G_INSTALL_PATH + "layouts/" + "layout-cycling.yaml", - self.G_LAYOUT_FILE, + default_layout_file = os.path.join( + self.G_INSTALL_PATH, default_layout_file ) - else: - shutil.copy("./layouts/layout-cycling.yaml", self.G_LAYOUT_FILE) + + shutil.copy(default_layout_file, self.G_LAYOUT_FILE) # font file - if self.G_FONT_FILE != "" or self.G_FONT_FILE != None: + if self.G_FONT_FILE: if os.path.exists(self.G_FONT_FILE): self.G_FONT_FULLPATH = self.G_FONT_FILE @@ -766,16 +766,13 @@ def __init__(self): ) self.G_MAP = "toner" if self.G_MAP_CONFIG[self.G_MAP]["use_mbtiles"] and not os.path.exists( - "maptile/{}.mbtiles".format(self.G_MAP) + os.path.join("maptile", f"{self.G_MAP}.mbtiles") ): self.G_MAP_CONFIG[self.G_MAP]["use_mbtiles"] = False self.loaded_dem = None - # mkdir - if not os.path.exists(self.G_SCREENSHOT_DIR): - os.mkdir(self.G_SCREENSHOT_DIR) - if not os.path.exists(self.G_LOG_DIR): - os.mkdir(self.G_LOG_DIR) + os.makedirs(self.G_SCREENSHOT_DIR, exist_ok=True) + os.makedirs(self.G_LOG_DIR, exist_ok=True) self.check_map_dir() @@ -812,7 +809,7 @@ def start_coroutine(self): self.logger.start_coroutine() self.display.start_coroutine() - # deley init start + # delay init start asyncio.create_task(self.delay_init()) async def delay_init(self): @@ -903,21 +900,21 @@ async def keyboard_check(self): self.logger.count_laps() elif key == "r": self.logger.reset_count() - elif key == "n" and self.gui != None: + elif key == "n" and self.gui is not None: self.gui.scroll_next() - elif key == "p" and self.gui != None: + elif key == "p" and self.gui is not None: self.gui.scroll_prev() - elif key == "q" and self.gui != None: + elif key == "q" and self.gui is not None: await self.quit() ##### temporary ##### # test hardware key signals - elif key == "," and self.gui != None: + elif key == "," and self.gui is not None: self.gui.press_tab() - elif key == "." and self.gui != None: + elif key == "." and self.gui is not None: self.gui.press_shift_tab() - elif key == "b" and self.gui != None: + elif key == "b" and self.gui is not None: self.gui.back_menu() - elif key == "c" and self.gui != None: + elif key == "c" and self.gui is not None: self.gui.get_screenshot() def set_logger(self, logger): @@ -927,31 +924,26 @@ def set_display(self, display): self.display = display def check_map_dir(self): - # mkdir (map) - if not self.G_MAP_CONFIG[self.G_MAP]["use_mbtiles"] and not os.path.exists( - "maptile/" + self.G_MAP - ): - os.mkdir("maptile/" + self.G_MAP) - # optional - if not self.G_MAP_CONFIG[self.G_MAP]["use_mbtiles"] and not os.path.exists( - "maptile/" + self.G_HEATMAP_OVERLAY_MAP - ): - os.mkdir("maptile/" + self.G_HEATMAP_OVERLAY_MAP) - if not os.path.exists("maptile/" + self.G_RAIN_OVERLAY_MAP): - os.mkdir("maptile/" + self.G_RAIN_OVERLAY_MAP) - if not os.path.exists("maptile/" + self.G_WIND_OVERLAY_MAP): - os.mkdir("maptile/" + self.G_WIND_OVERLAY_MAP) - if self.G_LOG_ALTITUDE_FROM_DATA_SOUCE and not os.path.exists( - "maptile/" + self.G_DEM_MAP - ): - os.mkdir("maptile/" + self.G_DEM_MAP) + if not self.G_MAP_CONFIG[self.G_MAP]["use_mbtiles"]: + os.makedirs(os.path.join("maptile", self.G_MAP), exist_ok=True) + # optional + os.makedirs( + os.path.join("maptile", self.G_HEATMAP_OVERLAY_MAP), exist_ok=True + ) + + os.makedirs(os.path.join("maptile", self.G_RAIN_OVERLAY_MAP), exist_ok=True) + os.makedirs(os.path.join("maptile", self.G_WIND_OVERLAY_MAP), exist_ok=True) + + if self.G_LOG_ALTITUDE_FROM_DATA_SOURCE: + os.makedirs(os.path.join("maptile", self.G_DEM_MAP), exist_ok=True) - def remove_maptiles(self, map_name): - path = "maptile/" + map_name + @staticmethod + def remove_maptiles(map_name): + path = os.path.join("maptile", map_name) if os.path.exists(path): files = os.listdir(path) - dir = [f for f in files if os.path.isdir(os.path.join(path, f))] - for d in dir: + dirs = [f for f in files if os.path.isdir(os.path.join(path, f))] + for d in dirs: shutil.rmtree(os.path.join(path, d)) def get_serial(self): @@ -987,7 +979,8 @@ def press_button(self, button_hard, press_button, index): def change_mode(self): self.button_config.change_mode() - def exec_cmd(self, cmd, cmd_print=True): + @staticmethod + def exec_cmd(cmd, cmd_print=True): if cmd_print: print(cmd) try: @@ -995,17 +988,15 @@ def exec_cmd(self, cmd, cmd_print=True): except: traceback.print_exc() - def exec_cmd_return_value(self, cmd, cmd_print=True): - string = "" + @staticmethod + def exec_cmd_return_value(cmd, cmd_print=True): if cmd_print: print(cmd) - ver = sys.version_info try: p = subprocess.run( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - # universal_newlines = True ) string = p.stdout.decode("utf8").strip() return string @@ -1031,7 +1022,7 @@ async def kill_tasks(self): async def quit(self): print("quit") - if self.ble_uart != None: + if self.ble_uart is not None: await self.ble_uart.quit() await self.network.quit() @@ -1064,12 +1055,12 @@ def reboot(self): def hardware_wifi_bt_on(self): if self.G_IS_RASPI: - cmd = [self.G_INSTALL_PATH + "scripts/comment_out.sh"] + cmd = [os.path.join(self.G_INSTALL_PATH, "scripts/comment_out.sh")] self.exec_cmd(cmd) def hardware_wifi_bt_off(self): if self.G_IS_RASPI: - cmd = [self.G_INSTALL_PATH + "scripts/uncomment.sh"] + cmd = [os.path.join(self.G_INSTALL_PATH, "scripts/uncomment.sh")] self.exec_cmd(cmd) def update_application(self): @@ -1090,7 +1081,7 @@ def detect_network(self): connect_interface.connect(("8.8.8.8", 53)) self.G_IP_ADDRESS = connect_interface.getsockname()[0] return True - except socket.error as ex: + except socket.error: self.G_IP_ADDRESS = "No address" return False @@ -1100,7 +1091,7 @@ def get_wifi_bt_status(self): status = {"wlan": False, "bluetooth": False} try: - # json opetion requires raspbian buster + # json option requires raspbian buster raw_status = self.exec_cmd_return_value( ["rfkill", "--json"], cmd_print=False ) @@ -1115,7 +1106,7 @@ def get_wifi_bt_status(self): return (status["wlan"], status["bluetooth"]) def onoff_wifi_bt(self, key=None): - # in future, manage with pycomman + # in the future, manage with pycomman if not self.G_IS_RASPI: return @@ -1133,15 +1124,14 @@ def onoff_wifi_bt(self, key=None): status["Wifi"], status["Bluetooth"] = self.get_wifi_bt_status() self.exec_cmd(onoff_cmd[key][status[key]]) - async def bluetooth_tethering(self, disconnect=False, cmd_print=True): + async def bluetooth_tethering(self, disconnect=False): if not self.G_IS_RASPI: return if self.G_BT_USE_ADDRESS == "": return - if self.bt_pan == None: + if self.bt_pan is None: return - res = None if not disconnect: res = await self.bt_pan.connect_tethering( self.G_BT_ADDRESS[self.G_BT_USE_ADDRESS] @@ -1150,10 +1140,7 @@ async def bluetooth_tethering(self, disconnect=False, cmd_print=True): res = await self.bt_pan.disconnect_tethering( self.G_BT_ADDRESS[self.G_BT_USE_ADDRESS] ) - if res != None and res: - return True - else: - return False + return bool(res) def check_time(self, log_str): t = datetime.datetime.now() @@ -1161,14 +1148,13 @@ def check_time(self, log_str): self.log_time = t def read_map_list(self): - text = None with open(self.G_MAP_LIST) as file: text = file.read() map_list = yaml.safe_load(text) - if map_list == None: + if map_list is None: return for key in map_list: - if map_list[key]["attribution"] == None: + if map_list[key]["attribution"] is None: map_list[key]["attribution"] = "" self.G_MAP_CONFIG.update(map_list) @@ -1233,7 +1219,8 @@ def get_dist_on_earth_hubeny(self, p0_lon, p0_lat, p1_lon, p1_lat): + (self.GEO_R1_2 / w) * c2 * (r0_lon - r1_lon) ** 2 ) - def calc_azimuth(self, lat, lon): + @staticmethod + def calc_azimuth(lat, lon): rad_latitude = np.radians(lat) rad_longitude = np.radians(lon) rad_longitude_delta = rad_longitude[1:] - rad_longitude[0:-1] @@ -1249,7 +1236,8 @@ def calc_azimuth(self, lat, lon): ).astype(dtype="int16") return azimuth - def get_maptile_filename(self, map_name, z, x, y): + @staticmethod + def get_maptile_filename(map_name, z, x, y): return "maptile/" + map_name + "/{0}/{1}/{2}.png".format(z, x, y) async def get_altitude_from_tile(self, pos): @@ -1280,7 +1268,8 @@ async def get_altitude_from_tile(self, pos): # print(altitude, filename, p_x, p_y, pos[1], pos[0]) return altitude - def get_tilexy_and_xy_in_tile(self, z, x, y, tile_size): + @staticmethod + def get_tilexy_and_xy_in_tile(z, x, y, tile_size): n = 2.0**z _y = math.radians(y) x_in_tile, tile_x = math.modf((x + 180.0) / 360.0 * n) @@ -1295,15 +1284,17 @@ def get_tilexy_and_xy_in_tile(self, z, x, y, tile_size): int(y_in_tile * tile_size), ) - def get_lon_lat_from_tile_xy(self, z, x, y): + @staticmethod + def get_lon_lat_from_tile_xy(z, x, y): n = 2.0**z lon = x / n * 360.0 - 180.0 lat = math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * y / n)))) return lon, lat + @staticmethod # replacement of dateutil.parser.parse - def datetime_myparser(self, ts): + def datetime_myparser(ts): if len(ts) == 14: # 20190322232414 / 14 chars dt = datetime.datetime( diff --git a/modules/display/dfrobot_rpi_display.py b/modules/display/dfrobot_rpi_display.py index e74a7357..87ce3d7f 100644 --- a/modules/display/dfrobot_rpi_display.py +++ b/modules/display/dfrobot_rpi_display.py @@ -1,16 +1,12 @@ -import time +_SENSOR_DISPLAY = False -import numpy as np -from PIL import Image +try: + from DFRobot_RPi_Display.devices.dfrobot_epaper import DFRobot_Epaper_SPI -_SENSOR_DISPLAY = False -# try: -from PIL import Image -from DFRobot_RPi_Display.devices.dfrobot_epaper import DFRobot_Epaper_SPI + _SENSOR_DISPLAY = True +except ImportError: + pass -_SENSOR_DISPLAY = True -# except: -# pass print(" DFRobot RPi Display : ", _SENSOR_DISPLAY) RASPBERRY_SPI_BUS = 0 diff --git a/modules/display/mip_display.py b/modules/display/mip_display.py index e365db0c..f368dd7f 100644 --- a/modules/display/mip_display.py +++ b/modules/display/mip_display.py @@ -1,6 +1,5 @@ import time -# import datetime import asyncio import numpy as np @@ -16,10 +15,10 @@ pyximport.install() from .cython.mip_helper import conv_3bit_color, MipDisplay_CPP - # MODE = "Cython" MODE = "Cython_full" -except: +except ImportError: pass + print(" MIP DISPLAY : ", _SENSOR_DISPLAY) @@ -170,7 +169,7 @@ def inversion(self, sec): async def draw_worker(self): while True: img_bytes = await self.draw_queue.get() - if img_bytes == None: + if img_bytes is None: break # self.config.check_time("mip_draw_worker start") # t = datetime.datetime.now() @@ -200,7 +199,7 @@ def update(self, im_array, direct_update): # print("diff ", int(len(diff_lines)/self.config.G_HEIGHT*100), "%") # print(" ") - if len(diff_lines) == 0: + if not len(diff_lines): return self.pre_img[diff_lines] = self.img_buff_rgb8[diff_lines] # self.config.check_time("diff_lines") diff --git a/modules/display/mip_sharp_display.py b/modules/display/mip_sharp_display.py index 599379b7..eec414e2 100644 --- a/modules/display/mip_sharp_display.py +++ b/modules/display/mip_sharp_display.py @@ -10,8 +10,9 @@ import pigpio _SENSOR_DISPLAY = True -except: +except ImportError: pass + print(" MIP SHARP DISPLAY : ", _SENSOR_DISPLAY) # https://qiita.com/hishi/items/669ce474fcd76bdce1f1 @@ -101,11 +102,11 @@ def inversion(self, sec): async def draw_worker(self): while True: img_bytes = await self.draw_queue.get() - if img_bytes == None: + if img_bytes is None: break self.pi.write(GPIO_SCS, 1) await asyncio.sleep(0.000006) - if len(img_bytes) > 0: + if len(img_bytes): self.pi.spi_write(self.spi, img_bytes) # dummy output for ghost line self.pi.spi_write(self.spi, [0x00000000, 0]) @@ -127,7 +128,7 @@ async def update(self, im_array, direct_update): # print("diff ", int(len(diff_lines)/self.config.G_HEIGHT*100), "%") # print(" ") - if len(diff_lines) == 0: + if not len(diff_lines): return self.pre_img[diff_lines] = self.img_buff_rgb8[diff_lines] # self.config.check_time("diff_lines") diff --git a/modules/display/papirus_display.py b/modules/display/papirus_display.py index c1dff692..4147d409 100644 --- a/modules/display/papirus_display.py +++ b/modules/display/papirus_display.py @@ -7,7 +7,7 @@ from papirus import Papirus _SENSOR_DISPLAY = True -except: +except ImportError: pass print(" PAPIRUS E-INK DISPLAY : ", _SENSOR_DISPLAY) diff --git a/modules/display/pitft_28_r.py b/modules/display/pitft_28_r.py index 0ad088b4..fe0c12bf 100644 --- a/modules/display/pitft_28_r.py +++ b/modules/display/pitft_28_r.py @@ -1,12 +1,5 @@ -import time -import datetime - -_SENSOR_DISPLAY = False -try: - # import RPi.GPIO as GPIO - _SENSOR_DISPLAY = True -except: - pass +_SENSOR_DISPLAY = True + print(" PiTFT 2.8(r) : ", _SENSOR_DISPLAY) # SCREEN diff --git a/modules/gui_config.py b/modules/gui_config.py index 83ca1901..c6cc9d7c 100644 --- a/modules/gui_config.py +++ b/modules/gui_config.py @@ -4,7 +4,7 @@ import PyQt6.QtCore as QtCore import PyQt6.QtWidgets as QtWidgets import PyQt6.QtGui as QtGui -except: +except ImportError: import PyQt5.QtCore as QtCore import PyQt5.QtWidgets as QtWidgets import PyQt5.QtGui as QtGui @@ -478,7 +478,6 @@ def set_qt5_or_qt6_constants(self, USE_PYQT6): self.format = self.format_mono def get_screen_shape(self, p): - screen_shape = None remove_bytes = 0 if self.config.display.has_color(): screen_shape = (p.height(), p.width(), 3) @@ -488,7 +487,6 @@ def get_screen_shape(self, p): return screen_shape, remove_bytes def read_layout(self): - text = None with open(self.config.G_LAYOUT_FILE) as file: text = file.read() self.G_LAYOUT = yaml.safe_load(text) diff --git a/modules/gui_pyqt.py b/modules/gui_pyqt.py index b882722a..09191ffb 100644 --- a/modules/gui_pyqt.py +++ b/modules/gui_pyqt.py @@ -1,7 +1,6 @@ import sys import os -# import platform import datetime import signal import asyncio @@ -14,7 +13,7 @@ import PyQt6.QtGui as QtGui USE_PYQT6 = True -except: +except ImportError: import PyQt5.QtCore as QtCore import PyQt5.QtWidgets as QtWidgets import PyQt5.QtGui as QtGui @@ -48,7 +47,7 @@ async def closeEvent(self, event): # override from QtWidget def paintEvent(self, event): - if self.gui != None: + if self.gui is not None: self.gui.draw_display() @@ -368,7 +367,7 @@ def delay_init(self): self.main_page.addWidget(self.map_widget) elif ( k == "CUESHEET" - and len(self.config.logger.course.point_name) > 0 + and len(self.config.logger.course.point_name) and self.config.G_COURSE_INDEXING and self.config.G_CUESHEET_DISPLAY_NUM > 0 ): @@ -382,7 +381,6 @@ def delay_init(self): # integrate main_layout self.main_layout.addWidget(self.main_page) if self.config.display.has_touch(): - # button from modules.pyqt.pyqt_button_box_widget import ButtonBoxWidget self.button_box_widget = ButtonBoxWidget(self.main_widget, self.config) @@ -423,14 +421,13 @@ def init_buffer(self): self.screen_shape, self.remove_bytes = self.gui_config.get_screen_shape(p) def exec(self): - # self.app.exec() with self.config.loop: self.config.loop.run_forever() # loop is stopped # loop is closed def add_font(self): - # default font (macOS is not allowed relative path) + # default font (macOS is not allowing relative paths) res = QtGui.QFontDatabase.addApplicationFont( "fonts/Yantramanav/Yantramanav-Black.ttf" ) @@ -626,10 +623,10 @@ def screenshot(self): filename = date.strftime("%Y-%m-%d_%H-%M-%S.png") print("screenshot:", filename) p = self.stack_widget.grab() - p.save(self.config.G_SCREENSHOT_DIR + filename, "png") + p.save(os.path.join(self.config.G_SCREENSHOT_DIR, filename), "png") def draw_display(self, direct_update=False): - if not self.config.display.send_display or self.stack_widget == None: + if not self.config.display.send_display or self.stack_widget is None: return # self.config.check_time("draw_display start") @@ -637,10 +634,10 @@ def draw_display(self, direct_update=False): # self.config.check_time("grab") ptr = p.constBits() - if ptr == None: + if ptr is None: return - if self.screen_image != None and p == self.screen_image: + if self.screen_image is not None and p == self.screen_image: return self.screen_image = p @@ -658,7 +655,7 @@ def draw_display(self, direct_update=False): # self.config.check_time("draw_display end") def change_start_stop_button(self, status): - if self.button_box_widget != None: + if self.button_box_widget is not None: self.button_box_widget.change_start_stop_button(status) def brightness_control(self): @@ -673,7 +670,7 @@ def change_menu_page(self, page, focus_reset=True): if not self.config.display.has_touch() and hasattr( self.stack_widget.widget(page), "focus_widget" ): - if focus_reset and self.stack_widget.widget(page).focus_widget != None: + if focus_reset and self.stack_widget.widget(page).focus_widget is not None: self.stack_widget.widget(page).focus_widget.setFocus() def change_menu_back(self): @@ -694,7 +691,7 @@ async def add_message_queue(self, title=None, message=None, fn=None): async def msg_worker(self): while True: msg = await self.msg_queue.get() - if msg == None: + if msg is None: break self.msg_queue.task_done() @@ -807,8 +804,8 @@ class DialogButton(QtWidgets.QPushButton): next_button = None prev_button = None - def focusNextPrevChild(self, next): - if next: + def focusNextPrevChild(self, is_next): + if is_next: self.next_button.setFocus() else: self.prev_button.setFocus() @@ -868,7 +865,7 @@ def back(): # title_label_width = title_label.fontMetrics().horizontalAdvance(title_label.text()) # title_icon - if title_icon != None: + if title_icon is not None: outer_widget = QtWidgets.QWidget(container) left_icon = QtWidgets.QLabel() @@ -879,7 +876,7 @@ def back(): label_layout.addWidget(left_icon) label_layout.addWidget(title_label, stretch=2) layout.addWidget(outer_widget) - elif message != None: + elif message is not None: outer_widget = QtWidgets.QWidget(container) font.setPointSize(int(fontsize * 1.5)) message_label = QtWidgets.QLabel(message, font=font) @@ -926,7 +923,7 @@ def back(): buttons[i].clicked.connect(background.deleteLater) # func with OK button - if fn != None: + if fn is not None: buttons[0].clicked.connect(fn) layout.addWidget(button_widget) diff --git a/modules/helper/api.py b/modules/helper/api.py index cc00a867..917534aa 100644 --- a/modules/helper/api.py +++ b/modules/helper/api.py @@ -20,7 +20,7 @@ ) _IMPORT_GARMINCONNECT = True -except: +except ImportError: pass _IMPORT_STRAVA_COOKIE = False @@ -28,7 +28,7 @@ from stravacookies import StravaCookieFetcher _IMPORT_STRAVA_COOKIE = True -except: +except ImportError: pass _IMPORT_THINGSBOARD = False @@ -36,7 +36,7 @@ from tb_device_mqtt import TBDeviceMqttClient, TBPublishInfo _IMPORT_THINGSBOARD = True -except: +except ImportError: pass @@ -134,13 +134,13 @@ async def get_ridewithgps_route(self, add=False, reset=False): params=self.config.G_RIDEWITHGPS_API["PARAMS"], ) user = response.get("user") - if user != None: + if user is not None: self.config.G_RIDEWITHGPS_API["USER_ID"] = user.get("id") - if self.config.G_RIDEWITHGPS_API["USER_ID"] == None: + if self.config.G_RIDEWITHGPS_API["USER_ID"] is None: return # get user route (total_num) - if self.config.G_RIDEWITHGPS_API["USER_ROUTES_NUM"] == None: + if self.config.G_RIDEWITHGPS_API["USER_ROUTES_NUM"] is None: response = await self.config.network.get_json( self.config.G_RIDEWITHGPS_API["URL_USER_ROUTES"].format( user=self.config.G_RIDEWITHGPS_API["USER_ID"], offset=0, limit=0 @@ -343,7 +343,7 @@ async def strava_upload(self): "Authorization": "Bearer " + self.config.G_STRAVA_API["ACCESS_TOKEN"] } data = {"data_type": "fit"} - async with aiofiles.open(self.config.G_UPLOAD_FILE, "rb") as file: + async with aiofiles.open(self.config.G_UPLOAD_FILE, "rb"): data["file"] = open(self.config.G_UPLOAD_FILE, "rb") upload_result = await self.config.network.post( self.config.G_STRAVA_API_URL["UPLOAD"], headers=headers, data=data @@ -496,7 +496,7 @@ def get_strava_cookie(self): traceback.print_exc() def thingsboard_check(self): - if self.thingsboard_client != None: + if self.thingsboard_client is not None: return True else: return False @@ -527,7 +527,7 @@ def check_livetrack(self): async def send_livetrack_data_internal(self, quick_send=False): t = int(time.time()) - bt_pan_status = False + if ( not quick_send and t - self.send_time < self.config.G_THINGSBOARD_API["INTERVAL_SEC"] @@ -613,7 +613,6 @@ async def send_livetrack_data_internal(self, quick_send=False): }, } - # self.thingsboard_client.disconnect() try: self.thingsboard_client.connect() res = self.thingsboard_client.send_telemetry(data).get() @@ -654,8 +653,8 @@ async def send_livetrack_data_internal(self, quick_send=False): def send_livetrack_course(self, reset=False): if not reset and ( - len(self.config.logger.course.latitude) == 0 - or len(self.config.logger.course.longitude) == 0 + not len(self.config.logger.course.latitude) + or not len(self.config.logger.course.longitude) ): return diff --git a/modules/helper/ble_gatt_server.py b/modules/helper/ble_gatt_server.py index 43653111..2ede401e 100644 --- a/modules/helper/ble_gatt_server.py +++ b/modules/helper/ble_gatt_server.py @@ -1,4 +1,3 @@ -import os import asyncio import json import re @@ -37,7 +36,7 @@ def __init__(self, config): super().__init__(self.service_uuid, True) async def quit(self): - if not self.status and self.bus != None: + if not self.status and self.bus is not None: self.bus.disconnect() # direct access from central @@ -47,18 +46,11 @@ def tx_characteristic(self, options): # notice to central def send_message(self, value): - # debug print self.tx_characteristic.changed(bytes(value + "\\n\n", "utf-8")) # receive from central @characteristic(rx_characteristic_uuid, CharFlags.WRITE).setter def rx_characteristic(self, value, options): - # debug - # try: - # print(value.decode()) - # except: - # print(value) - if value[0] == 0x10: self.value = bytearray() self.value_extend = True @@ -76,7 +68,7 @@ def rx_characteristic(self, value, options): res = re.match( "^setTime\((\d+)\);E.setTimeZone\((\S+)\)", self.timestamp_str ) - if res != None: + if res is not None: self.timestamp_done = True self.timestamp_status = False time_diff = datetime.timedelta(hours=float(res.group(2))) @@ -86,7 +78,6 @@ def rx_characteristic(self, value, options): if self.value_extend: self.value.extend(bytearray(value)) - # self.value.extend(bytearray(value)) # for gadgetbridge JSON message if ( diff --git a/modules/helper/bt_pan.py b/modules/helper/bt_pan.py index c243eb61..27f6fe76 100644 --- a/modules/helper/bt_pan.py +++ b/modules/helper/bt_pan.py @@ -11,7 +11,7 @@ from dbus_next import Variant HAS_DBUS_NEXT = True -except: +except ImportError: pass try: @@ -19,7 +19,7 @@ import dbus HAS_DBUS = True -except: +except ImportError: pass @@ -89,8 +89,6 @@ async def initialize_device(self, remote_addr): return True async def connect_tethering(self, remote_addr): - connected = None - if not await self.initialize_device(remote_addr): return False @@ -98,7 +96,6 @@ async def connect_tethering(self, remote_addr): try: await self.interface.call_connect(self.service_uuid) except DBusError as e: - # error = e.get_dbus_name() print(e) await asyncio.sleep(1) else: @@ -108,15 +105,12 @@ async def connect_tethering(self, remote_addr): return connected async def disconnect_tethering(self, remote_addr): - connected = None - if not await self.initialize_device(remote_addr): return False try: await self.interface.call_disconnect() except DBusError as e: - # error = e.get_dbus_name() print(e) connected = await self.interface.get_connected() @@ -173,7 +167,6 @@ def initialize_device(self, remote_addr): return True async def connect_tethering(self, remote_addr): - connected = None if not self.initialize_device(remote_addr): return False @@ -184,8 +177,6 @@ async def connect_tethering(self, remote_addr): error = e.get_dbus_name() print(error) await asyncio.sleep(1) - #'org.freedesktop.DBus.Error.NoReply' - #'org.bluez.Error.Failed' else: break connected = self.prop_get(self.interface, "Connected") @@ -193,7 +184,6 @@ async def connect_tethering(self, remote_addr): return connected async def disconnect_tethering(self, remote_addr): - connected = None if not self.initialize_device(remote_addr): return False @@ -202,8 +192,6 @@ async def disconnect_tethering(self, remote_addr): except dbus.exceptions.DBusException as e: error = e.get_dbus_name() print(error) - #'org.bluez.Error.NotConnected' - #'org.bluez.Error.Failed' connected = self.prop_get(self.interface, "Connected") return connected diff --git a/modules/helper/network.py b/modules/helper/network.py index 8118c14f..3a056fd1 100644 --- a/modules/helper/network.py +++ b/modules/helper/network.py @@ -23,7 +23,8 @@ def __init__(self, config): async def quit(self): await self.download_queue.put(None) - async def get_json(self, url, params=None, headers=None, timeout=10): + @staticmethod + async def get_json(url, params=None, headers=None, timeout=10): async with aiohttp.ClientSession() as session: async with session.get( url, params=params, headers=headers, timeout=timeout @@ -31,7 +32,8 @@ async def get_json(self, url, params=None, headers=None, timeout=10): json = await res.json() return json - async def post(self, url, headers=None, params=None, data=None): + @staticmethod + async def post(url, headers=None, params=None, data=None): async with aiohttp.ClientSession() as session: async with session.post( url, headers=headers, params=params, data=data @@ -44,7 +46,7 @@ async def download_worker(self): # for urls, header, save_paths, params: while True: q = await self.download_queue.get() - if q == None: + if q is None: break try: res = await self.download_files(**q) @@ -53,15 +55,15 @@ async def download_worker(self): return # all False -> give up - if not any(res) or res == None: + if not any(res) or res is None: failed.append((datetime.datetime.now(), q)) print("failed download") print(q["urls"]) # retry elif ( not all(res) - and len(q["urls"]) > 0 - and len(res) > 0 + and len(q["urls"]) + and len(res) and len(q["urls"]) == len(res) ): retry_urls = [] @@ -70,7 +72,7 @@ async def download_worker(self): if not status: retry_urls.append(url) retry_save_paths.append(save_path) - if len(retry_urls) > 0: + if len(retry_urls): q["urls"] = retry_urls q["save_paths"] = retry_save_paths await self.download_queue.put(q) @@ -78,7 +80,7 @@ async def download_worker(self): async def download_maptile( self, map_config, map_name, z, tiles, additional_download=False ): - if not self.config.detect_network() or map_config[map_name]["url"] == None: + if not self.config.detect_network() or map_config[map_name]["url"] is None: return False urls = [] @@ -98,8 +100,8 @@ async def download_maptile( self.config.G_WIND_OVERLAY_MAP_CONFIG, ]: if ( - map_config[map_name]["basetime"] == None - or map_config[map_name]["validtime"] == None + map_config[map_name]["basetime"] is None + or map_config[map_name]["validtime"] is None ): return False additional_var["basetime"] = map_config[map_name]["basetime"] @@ -108,19 +110,19 @@ async def download_maptile( map_config == self.config.G_WIND_OVERLAY_MAP_CONFIG and "jpn_scw" in map_name ): - if map_config[map_name]["subdomain"] == None: + if map_config[map_name]["subdomain"] is None: return False additional_var["subdomain"] = map_config[map_name]["subdomain"] # make header if ( "referer" in map_config[map_name] - and map_config[map_name]["referer"] != None + and map_config[map_name]["referer"] is not None ): request_header["Referer"] = map_config[map_name]["referer"] if ( "user_agent" in map_config[map_name] - and map_config[map_name]["user_agent"] != None + and map_config[map_name]["user_agent"] is not None ): request_header["User-Agent"] = map_config[map_name]["user_agent"] @@ -201,7 +203,7 @@ async def download_maptile( ) ) - if len(additional_urls) > 0: + if len(additional_urls): await self.download_queue.put( { "urls": additional_urls, @@ -212,7 +214,8 @@ async def download_maptile( return True - async def get_http_request(self, session, url, save_path, headers, params): + @staticmethod + async def get_http_request(session, url, save_path, headers, params): try: async with session.get(url, headers=headers, params=params) as dl_file: if dl_file.status == 200: @@ -228,7 +231,6 @@ async def get_http_request(self, session, url, save_path, headers, params): async def download_files(self, urls, save_paths, headers=None, params=None): tasks = [] - res = None async with asyncio.Semaphore(self.config.G_COROUTINE_SEM): async with aiohttp.ClientSession() as session: for url, save_path in zip(urls, save_paths): diff --git a/modules/logger/cython/crc16_p.py b/modules/logger/cython/crc16_p.py index 556b0f2b..ad51426f 100644 --- a/modules/logger/cython/crc16_p.py +++ b/modules/logger/cython/crc16_p.py @@ -1,5 +1,4 @@ def crc16(data): - # if self.config.G_IS_DEBUG: print(data) crc = 0 crc_table = [ 0x0000, diff --git a/modules/logger/loader_tcx.py b/modules/logger/loader_tcx.py index 5a1045b9..4ce45375 100644 --- a/modules/logger/loader_tcx.py +++ b/modules/logger/loader_tcx.py @@ -5,20 +5,18 @@ import shutil import re -# import xml.etree.ElementTree as ET from math import factorial from crdp import rdp import numpy as np -import importlib POLYLINE_DECODER = False try: import polyline POLYLINE_DECODER = True -except: +except ImportError: pass @@ -71,7 +69,9 @@ def reset(self, delete_course_file=False, replace=False): self.slope = np.array([]) self.slope_smoothing = np.array([]) self.colored_altitude = np.array([]) - self.climb_segment = [] + self.climb_segment = ( + [] + ) # [start_index, end_index, distance, average_grade, volume(=dist*average), cat] # for course points self.point_name = np.array([]) @@ -112,7 +112,7 @@ def load(self): t2 = datetime.datetime.now() time_profile.append((t2 - t1).total_seconds()) - if len(self.latitude) == 0: + if not len(self.latitude): return print() print("[logger] Loading course:") @@ -172,7 +172,7 @@ def get_courses(self): # } dir_list = sorted( - glob.glob(self.config.G_COURSE_DIR + "/*.tcx"), + glob.glob(os.path.join(self.config.G_COURSE_DIR, "*.tcx")), key=lambda f: os.stat(f).st_mtime, reverse=True, ) @@ -185,8 +185,8 @@ def get_courses(self): courses = [] for c in file_list: info = { - "id": c[len(self.config.G_COURSE_DIR) :], - "name": c[len(self.config.G_COURSE_DIR) :], + "path": c, + "name": os.path.basename(c), } # heavy: delayed updates required # with open(c, 'r', encoding="utf-8_sig") as f: @@ -343,17 +343,17 @@ def read_tcx(self): return # delete 'Straight' of course points - if len(self.point_type) > 0: + if len(self.point_type): ptype = np.array(self.point_type) not_straight_cond = np.where(ptype != "Straight", True, False) self.point_type = list(ptype[not_straight_cond]) - if len(self.point_name) > 0: + if len(self.point_name): self.point_name = list(np.array(self.point_name)[not_straight_cond]) - if len(self.point_latitude) > 0: + if len(self.point_latitude): self.point_latitude = np.array(self.point_latitude)[not_straight_cond] - if len(self.point_longitude) > 0: + if len(self.point_longitude): self.point_longitude = np.array(self.point_longitude)[not_straight_cond] - if len(self.point_notes) > 0: + if len(self.point_notes): self.point_notes = list(np.array(self.point_notes)[not_straight_cond]) async def get_google_route_from_mapstogpx(self, url): @@ -438,9 +438,9 @@ async def get_google_route_from_mapstogpx(self, url): return async def get_google_route(self, x1, y1, x2, y2): - json_routes = await self.config.network.api.get_google_route(x1, y1, x2, y2) - # print(json_routes) - if not POLYLINE_DECODER or json_routes == None or json_routes["status"] != "OK": + json_routes = await self.config.network.api.get_google_routes(x1, y1, x2, y2) + + if not POLYLINE_DECODER or json_routes is None or json_routes["status"] != "OK": return self.info["Name"] = "Google routes" @@ -511,7 +511,7 @@ def downsample(self): len_dist = len(self.distance) # empty check - if len_lat == 0 and len_lon == 0 and len_alt == 0 and len_dist == 0: + if not len_lat and not len_lon and not len_alt and not len_dist: return try: @@ -522,7 +522,7 @@ def downsample(self): return_mask=True, ) ) - if len_alt > 0 and len_dist > 0: + if len_alt and len_dist: cond = cond | np.array( rdp( np.column_stack([self.distance, self.altitude]), @@ -532,9 +532,9 @@ def downsample(self): ) self.latitude = self.latitude[cond] self.longitude = self.longitude[cond] - if len_alt > 0: + if len_alt: self.altitude = self.altitude[cond] # [m] - if len_dist > 0: + if len_dist: self.distance = self.distance[cond] / 1000 # [km] except: self.distance = self.distance / 1000 # [km] @@ -547,7 +547,7 @@ def downsample(self): ) self.points_diff_dist = np.sqrt(self.points_diff_sum_of_squares) - if len_dist == 0: + if not len_dist: self.distance = ( self.config.get_dist_on_earth_array( self.longitude[0:-1], @@ -561,7 +561,7 @@ def downsample(self): self.distance = np.cumsum(self.distance) dist_diff = 1000 * np.diff(self.distance) # [m] - if len_alt > 0: + if len_alt: modified_altitude = self.savitzky_golay(self.altitude, 53, 3) # do not apply if length is different (occurs when too short course) if len(self.altitude) == len(modified_altitude): @@ -653,7 +653,6 @@ def calc_slope_smoothing(self): slope_smoothing_cat, ) - # self.climb_segment = [] #[start_index, end_index, distance, average_grade, volume(=dist*average), cat] climb_search_state = False climb_start_cutoff = 2 climb_end_cutoff = 1 @@ -752,9 +751,9 @@ def modify_course_points(self): len_alt = len(self.altitude) # calculate course point distance - if len_pnt_dist == 0 and len_dist > 0: + if not len_pnt_dist and len_dist: self.point_distance = np.empty(len_pnt_lat) - if len_pnt_alt == 0 and len_alt > 0: + if not len_pnt_alt and len_alt: self.point_altitude = np.zeros(len_pnt_lat) min_index = 0 @@ -796,7 +795,7 @@ def modify_course_points(self): dist_diff_h < self.config.G_GPS_ON_ROUTE_CUTOFF and dist_diff_h < min_dist_diff_h ): - if min_j != None and j - min_j > 2: + if min_j is not None and j - min_j > 2: continue min_j = j min_dist_diff_h = dist_diff_h @@ -809,7 +808,7 @@ def modify_course_points(self): ) / 1000 ) - if len_alt > 0: + if len_alt: min_alt_delta = ( ( self.altitude[min_index + j + 1] @@ -822,17 +821,17 @@ def modify_course_points(self): * min_dist_delta ) - if min_j == None: + if min_j is None: min_j = 0 min_index = min_index + min_j - if len_pnt_dist == 0 and len_dist > 0: + if not len_pnt_dist and len_dist: self.point_distance[i] = self.distance[min_index] + min_dist_delta - if len_pnt_alt == 0 and len_alt > 0: + if not len_pnt_alt and len_alt: self.point_altitude[i] = self.altitude[min_index] + min_alt_delta # add climb tops - # if len(self.climb_segment) > 0: + # if len(self.climb_segment): # min_index = 0 # for i in range(len(self.climb_segment)): # diff_dist = np.abs(self.point_distance - self.climb_segment[i]['course_point_distance']) @@ -848,26 +847,21 @@ def modify_course_points(self): len_pnt_alt = len(self.point_altitude) # add start course point - if ( - len_pnt_lat > 0 - and len_pnt_dist > 0 - and len_dist > 0 - and self.point_distance[0] != 0.0 - ): + if len_pnt_lat and len_pnt_dist and len_dist and self.point_distance[0] != 0.0: self.point_name.insert(0, "Start") self.point_latitude = np.insert(self.point_latitude, 0, self.latitude[0]) self.point_longitude = np.insert(self.point_longitude, 0, self.longitude[0]) self.point_type.insert(0, "") - if len_pnt_dist > 0 and len_dist > 0: + if len_pnt_dist and len_dist: self.point_distance = np.insert(self.point_distance, 0, 0.0) - if len_pnt_alt > 0 and len_alt > 0: + if len_pnt_alt and len_alt: self.point_altitude = np.insert( self.point_altitude, 0, self.altitude[0] ) # add end course point # print(self.point_latitude, self.latitude, self.point_longitude, self.longitude) end_distance = None - if len(self.latitude) > 0 and len(self.point_longitude) > 0: + if len(self.latitude) and len(self.point_longitude): end_distance = self.config.get_dist_on_earth_array( self.longitude[-1], self.latitude[-1], @@ -875,30 +869,31 @@ def modify_course_points(self): self.point_latitude[-1], ) if ( - len_pnt_lat > 0 - and len_pnt_dist > 0 - and len_dist > 0 - and end_distance != None + len_pnt_lat + and len_pnt_dist + and len_dist + and end_distance is not None and end_distance > 5 ): self.point_name.append("End") self.point_latitude = np.append(self.point_latitude, self.latitude[-1]) self.point_longitude = np.append(self.point_longitude, self.longitude[-1]) self.point_type.append("") - if len_pnt_dist > 0 and len_dist > 0: + if len_pnt_dist and len_dist: self.point_distance = np.append(self.point_distance, self.distance[-1]) - if len_pnt_alt > 0 and len_alt > 0: + if len_pnt_alt and len_alt: self.point_altitude = np.append(self.point_altitude, self.altitude[-1]) self.point_name = np.array(self.point_name) self.point_type = np.array(self.point_type) self.point_name = np.array(self.point_name) - def savitzky_golay(self, y, window_size, order, deriv=0, rate=1): + @staticmethod + def savitzky_golay(y, window_size, order, deriv=0, rate=1): try: window_size = np.abs(np.intc(window_size)) order = np.abs(np.intc(order)) - except ValueError as msg: + except ValueError: raise ValueError("window_size and order have to be of type int") if window_size % 2 != 1 or window_size < 1: raise TypeError("window_size size must be a positive odd number") diff --git a/modules/logger/logger.py b/modules/logger/logger.py index 72f1a105..c17393e0 100644 --- a/modules/logger/logger.py +++ b/modules/logger/logger.py @@ -1,6 +1,3 @@ -import datetime - - class Logger: config = None diff --git a/modules/logger/logger_csv.py b/modules/logger/logger_csv.py index 029bb17f..c0a32489 100644 --- a/modules/logger/logger_csv.py +++ b/modules/logger/logger_csv.py @@ -18,10 +18,7 @@ class config_local: class LoggerCsv(Logger): def write_log(self): # get start date - start_date = None - start_date_str = "errordate" ## SQLite - # con = sqlite3.connect(self.config.G_LOG_DB) con = sqlite3.connect( self.config.G_LOG_DB, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES, @@ -30,7 +27,7 @@ def write_log(self): cur = con.cursor() cur.execute("SELECT timestamp, MIN(timestamp) FROM BIKECOMPUTER_LOG") first_row = cur.fetchone() - if first_row != None: + if first_row is not None: start_date = first_row[0] else: return False @@ -47,7 +44,7 @@ def write_log(self): # voltage_battery,current_battery,voltage_out,current_out,battery_percentage\ # " # if sqlite3 command exists, use this command (much faster) - if shutil.which("sh") != None and shutil.which("sqlite3"): + if shutil.which("sh") is not None and shutil.which("sqlite3"): cur.close() con.close() sql_cmd = ( @@ -61,7 +58,6 @@ def write_log(self): sqlite3_cmd = ["sh", "-c", sql_cmd] self.config.exec_cmd(sqlite3_cmd) else: - # file open f = open(filename, "w", encoding="UTF-8") # get Lap Records @@ -73,7 +69,6 @@ def write_log(self): cur.close() con.close() - # success return True diff --git a/modules/logger/logger_fit.py b/modules/logger/logger_fit.py index 28db803b..3a1bdf87 100644 --- a/modules/logger/logger_fit.py +++ b/modules/logger/logger_fit.py @@ -7,7 +7,8 @@ from .logger import Logger # cython -MODE = "" +MODE = "Python" + try: import pyximport @@ -20,11 +21,9 @@ ) MODE = "Cython" -except: +except ImportError: from .cython.crc16_p import crc16 - MODE = "Python" - class config_local: G_LOG_DB = "./log/log.db~" @@ -193,7 +192,8 @@ def reset(self): } self.struct_def_cache = {} - def base_type_id_from_string(self, base_type_name): + @staticmethod + def base_type_id_from_string(base_type_name): return { "enum": 0x00, # 0 "sint8": 0x01, # 1 @@ -212,11 +212,13 @@ def base_type_id_from_string(self, base_type_name): "byte": 0x0D, }[base_type_name] - def base_type_size_from_id(self, base_type_id): + @staticmethod + def base_type_size_from_id(base_type_id): # 0 1 2 3 4 5 6 7 8 910111213 return [1, 1, 1, 2, 2, 4, 4, 1, 4, 8, 1, 2, 4, 1][base_type_id & 0xF] - def base_type_format_from_id(self, base_type_id): + @staticmethod + def base_type_format_from_id(base_type_id): # 01234567890123 return "BbBhHiIsfdBHIs"[base_type_id & 0xF] @@ -235,7 +237,6 @@ def write_log(self): def write_log_python(self): ## SQLite - # con = sqlite3.connect(self.config.G_LOG_DB) con = sqlite3.connect( self.config.G_LOG_DB, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES, @@ -244,19 +245,17 @@ def write_log_python(self): cur = con.cursor() # get start_date - start_date = None # get datetime object (timestamp) cur.execute("SELECT timestamp, MIN(timestamp) FROM BIKECOMPUTER_LOG") first_row = cur.fetchone() - if first_row != None: + if first_row is not None: start_date = first_row[0] else: return False # get end_date - end_date = None cur.execute("SELECT timestamp, MAX(timestamp) FROM BIKECOMPUTER_LOG") first_row = cur.fetchone() - if first_row != None: + if first_row is not None: end_date = first_row[0] else: return False @@ -318,17 +317,17 @@ def write_log_python(self): available_data = [] if None in row: for i, v in enumerate(row): - if v == None: + if v is None: continue available_fields.append(record_index[i]) available_data.append( self.convertValue((v,), message_num, record_index[i]) ) - # available_fields = [j for i, j in zip(row, record_index) if i != None] - # available_data = list(map(self.convertValue, [(i,) for i in row if i != None], [message_num]*len(available_fields), available_fields)) + # available_fields = [j for i, j in zip(row, record_index) if i is not None] + # available_data = list(map(self.convertValue, [(i,) for i in row if i is not None], [message_num]*len(available_fields), available_fields)) - # available_data_gen = [(self.convertValue((i,),message_num,j), j) for i, j in zip(row, record_index) if i != None] + # available_data_gen = [(self.convertValue((i,),message_num,j), j) for i, j in zip(row, record_index) if i is not None] # available_fields = [row[1] for row in available_data_gen] # available_data = [row[0] for row in available_data_gen] else: @@ -463,7 +462,6 @@ def write_definition(self, local_message_num): self.write(struct.pack("= 5 and res[4] != self.create_table_sql: + if res is not None and len(res) >= 5 and res[4] != self.create_table_sql: log_db_moved = self.config.G_LOG_DB + "-old_layout" self.cur.close() self.con.close() @@ -275,7 +275,7 @@ def init_db(self): self.con = sqlite3.connect(self.config.G_LOG_DB, check_same_thread=False) self.cur = self.con.cursor() replace_flg = True - if res == None or replace_flg: + if res is None or replace_flg: self.con.execute(self.create_table_sql) self.cur.execute("CREATE INDEX lap_index ON BIKECOMPUTER_LOG(lap)") self.cur.execute( @@ -306,9 +306,9 @@ def start_and_stop_manual(self): print("->M START {}".format(time_str)) self.start_and_stop("STOP") self.config.G_MANUAL_STATUS = "START" - if self.config.gui != None: + if self.config.gui is not None: self.config.gui.change_start_stop_button(self.config.G_MANUAL_STATUS) - if self.values["start_time"] == None: + if self.values["start_time"] is None: self.values["start_time"] = int(datetime.datetime.utcnow().timestamp()) if pre_status == "INIT" and not np.isnan( @@ -328,7 +328,7 @@ def start_and_stop_manual(self): print("->M STOP {}".format(time_str)) self.start_and_stop("START") self.config.G_MANUAL_STATUS = "STOP" - if self.config.gui != None: + if self.config.gui is not None: self.config.gui.change_start_stop_button(self.config.G_MANUAL_STATUS) self.config.setting.set_config_pickle( @@ -343,7 +343,7 @@ def start_and_stop_manual(self): self.config.gui.show_popup(self.config.G_MANUAL_STATUS + popup_extra) def start_and_stop(self, status=None): - if status != None: + if status is not None: self.config.G_STOPWATCH_STATUS = status time_str = datetime.datetime.now().strftime("%Y%m%d %H:%M:%S") if self.config.G_STOPWATCH_STATUS != "START": @@ -658,7 +658,7 @@ async def record_log(self): def calc_gross(self): # elapsed_time - if self.values["start_time"] == None: + if self.values["start_time"] is None: return # [s] self.values["elapsed_time"] = int( @@ -766,7 +766,7 @@ def resume(self): max_value = list(self.cur.fetchone()) for i, k in enumerate(main_item): self.record_stats["entire_max"][k] = 0 - if max_value[i] != None: + if max_value[i] is not None: self.record_stats["entire_max"][k] = max_value[i] # get lap max @@ -776,7 +776,7 @@ def resume(self): max_value = list(self.cur.fetchone()) for i, k in enumerate(main_item): self.record_stats["lap_max"][k] = 0 - if max_value[i] != None: + if max_value[i] is not None: self.record_stats["lap_max"][k] = max_value[i] # get pre lap @@ -813,7 +813,7 @@ def resume(self): # start_time self.cur.execute("SELECT MIN(timestamp) FROM BIKECOMPUTER_LOG") first_row = self.cur.fetchone() - if first_row[0] != None: + if first_row[0] is not None: self.values["start_time"] = int( self.config.datetime_myparser(first_row[0]).timestamp() - 1 ) @@ -830,10 +830,10 @@ def store_short_log_for_update_track(self, dist, lat, lon, timestamp): return if lat == self.config.G_GPS_NULLVALUE or lon == self.config.G_GPS_NULLVALUE: return - if len(self.short_log_dist) > 0 and self.short_log_dist[-1] == dist: + if len(self.short_log_dist) and self.short_log_dist[-1] == dist: return - if (len(self.short_log_lat) > 0 and self.short_log_lat[-1] == lat) and ( - len(self.short_log_lon) > 0 and self.short_log_lon[-1] == lon + if (len(self.short_log_lat) and self.short_log_lat[-1] == lat) and ( + len(self.short_log_lon) and self.short_log_lon[-1] == lon ): return if len(self.short_log_lat) > self.short_log_limit: @@ -866,7 +866,7 @@ def update_track(self, timestamp): # t = datetime.datetime.utcnow() timestamp_delta = None - if timestamp != None: + if timestamp is not None: timestamp_delta = (datetime.datetime.utcnow() - timestamp).total_seconds() # make_tmp_db = False @@ -875,14 +875,14 @@ def update_track(self, timestamp): dist_raw = np.array([]) # get values from short_log to db in logging - if timestamp_delta != None and self.short_log_available: + if timestamp_delta is not None and self.short_log_available: while self.short_log_lock: print("locked: get values") time.sleep(0.02) lat_raw = np.array(self.short_log_lat) lon_raw = np.array(self.short_log_lon) dist_raw = np.array(self.short_log_dist) - if len(self.short_log_lon) > 0: + if len(self.short_log_lon): timestamp_new = self.short_log_timestamp[-1] self.clear_short_log() self.short_log_available = True @@ -895,14 +895,14 @@ def update_track(self, timestamp): "SELECT distance,position_lat,position_long FROM BIKECOMPUTER_LOG " + "WHERE position_lat is not null AND position_long is not null " ) - if timestamp != None: + if timestamp is not None: query = query + "AND timestamp > '%s'" % timestamp con = sqlite3.connect(db_file) cur = con.cursor() cur.execute(query) res_array = np.array(cur.fetchall()) - if len(res_array.shape) > 0 and res_array.shape[0] > 0: + if len(res_array.shape) and res_array.shape[0] > 0: dist_raw = res_array[:, 0].astype("float32") # [m] lat_raw = res_array[:, 1].astype("float32") lon_raw = res_array[:, 2].astype("float32") @@ -910,7 +910,7 @@ def update_track(self, timestamp): # timestamp cur.execute("SELECT MAX(timestamp) FROM BIKECOMPUTER_LOG") first_row = cur.fetchone() - if first_row[0] != None: + if first_row[0] is not None: timestamp_new = self.config.datetime_myparser(first_row[0]) cur.close() @@ -919,7 +919,7 @@ def update_track(self, timestamp): self.short_log_available = True # print("lat_raw", len(lat_raw)) - if len(lat_raw) > 0 and (len(lat_raw) == len(lon_raw) == len(dist_raw)): + if len(lat_raw) and (len(lat_raw) == len(lon_raw) == len(dist_raw)): # downsampling try: cond = np.array( diff --git a/modules/pyqt/graph/pyqt_base_map.py b/modules/pyqt/graph/pyqt_base_map.py index fb43fb8b..8f6560ab 100644 --- a/modules/pyqt/graph/pyqt_base_map.py +++ b/modules/pyqt/graph/pyqt_base_map.py @@ -4,7 +4,7 @@ import PyQt6.QtCore as QtCore import PyQt6.QtWidgets as QtWidgets import PyQt6.QtGui as QtGui -except: +except ImportError: import PyQt5.QtCore as QtCore import PyQt5.QtWidgets as QtWidgets import PyQt5.QtGui as QtGui @@ -199,7 +199,7 @@ async def zoom_minus(self): await self.update_extra() def get_max_zoom(self): - if len(self.config.logger.course.distance) == 0: + if not len(self.config.logger.course.distance): return if self.config.G_MAX_ZOOM != 0: diff --git a/modules/pyqt/graph/pyqt_course_profile.py b/modules/pyqt/graph/pyqt_course_profile.py index 6aedac50..f94c85e7 100644 --- a/modules/pyqt/graph/pyqt_course_profile.py +++ b/modules/pyqt/graph/pyqt_course_profile.py @@ -5,7 +5,7 @@ import PyQt6.QtCore as QtCore import PyQt6.QtWidgets as QtWidgets import PyQt6.QtGui as QtGui -except: +except ImportError: import PyQt5.QtCore as QtCore import PyQt5.QtWidgets as QtWidgets import PyQt5.QtGui as QtGui @@ -61,9 +61,8 @@ def add_extra(self): # load course profile and display def load_course(self): - if ( - len(self.config.logger.course.distance) == 0 - or len(self.config.logger.course.altitude) == 0 + if not len(self.config.logger.course.distance) or not len( + self.config.logger.course.altitude ): return @@ -126,9 +125,8 @@ def load_course(self): def reset_course(self): for p in [self.course_profile_plot, self.climb_top_plot, self.climb_detail]: - if p != None: + if p is not None: self.plot.removeItem(p) - p = None self.plot.removeItem(self.current_point) def init_course(self): @@ -136,9 +134,8 @@ def init_course(self): self.resizeEvent(None) async def update_extra(self): - if ( - len(self.config.logger.course.distance) == 0 - or len(self.config.logger.course.altitude) == 0 + if not len(self.config.logger.course.distance) or not len( + self.config.logger.course.altitude ): return @@ -151,12 +148,11 @@ async def update_extra(self): return # remove current position for reloading - if len(self.location) > 0: + if len(self.location): self.plot.removeItem(self.current_point) self.location.pop() # initialize - x_start = x_end = np.nan x_width = self.zoom / 1000 dist_end = self.config.logger.course.distance[-1] self.graph_index = self.gps_values["course_index"] @@ -188,7 +184,6 @@ async def update_extra(self): ) x_end = self.map_pos["x"] + x_width - x_end_index = 0 if x_end >= dist_end: x_end_index = len(self.config.logger.course.distance) - 1 self.map_pos["x_index"] = self.gps_sensor.get_index_with_distance_cutoff( @@ -244,7 +239,7 @@ async def update_extra(self): y_max = int((y_max + y_range_space) / 50 + 2) * 50 self.plot.setYRange(min=y_min, max=y_max, padding=0) - if self.climb_detail != None: + if self.climb_detail is not None: self.plot.removeItem(self.climb_detail) climb_index = None @@ -257,7 +252,7 @@ async def update_extra(self): climb_index = i break - if climb_index == None: + if climb_index is None: self.climb_detail.setHtml("") else: summit_img = '' diff --git a/modules/pyqt/graph/pyqt_map.py b/modules/pyqt/graph/pyqt_map.py index aa426d00..6a23eb4c 100644 --- a/modules/pyqt/graph/pyqt_map.py +++ b/modules/pyqt/graph/pyqt_map.py @@ -11,7 +11,7 @@ import PyQt6.QtCore as QtCore import PyQt6.QtWidgets as QtWidgets import PyQt6.QtGui as QtGui -except: +except ImportError: import PyQt5.QtCore as QtCore import PyQt5.QtWidgets as QtWidgets import PyQt5.QtGui as QtGui @@ -157,7 +157,7 @@ def setup_ui_extra(self): # self.load_course() t = datetime.datetime.utcnow() self.get_track() # heavy when resume - if len(self.tracks_lon) != 0: + if len(self.tracks_lon): print( "resume_track(init): {:.3f} sec".format( (datetime.datetime.utcnow() - t).total_seconds() @@ -247,11 +247,11 @@ def add_extra(self): def init_cuesheet_and_instruction(self): # init cuesheet_widget if ( - len(self.config.logger.course.point_name) > 0 + len(self.config.logger.course.point_name) and self.config.G_CUESHEET_DISPLAY_NUM > 0 and self.config.G_COURSE_INDEXING ): - if self.cuesheet_widget == None: + if self.cuesheet_widget is None: self.cuesheet_widget = CueSheetWidget(self, self.config) self.cuesheet_widget.hide() # adhoc # self.map_cuesheet_ratio = 0.7 @@ -269,7 +269,7 @@ def init_cuesheet_and_instruction(self): def resizeEvent(self, event): if ( - len(self.config.logger.course.point_name) == 0 + not len(self.config.logger.course.point_name) or self.config.G_CUESHEET_DISPLAY_NUM == 0 or not self.config.G_COURSE_INDEXING ): @@ -303,13 +303,13 @@ def switch_lock(self): super().switch_lock() def load_course(self): - if len(self.config.logger.course.latitude) == 0: + if not len(self.config.logger.course.latitude): return time_profile = [] t1 = datetime.datetime.now() - if self.course_plot != None: + if self.course_plot is not None: self.plot.removeItem(self.course_plot) self.course_plot = CoursePlotItem( x=self.config.logger.course.longitude, @@ -322,7 +322,7 @@ def load_course(self): # test if not self.config.G_IS_RASPI: - if self.plot_verification != None: + if self.plot_verification is not None: self.plot.removeItem(self.plot_verification) self.plot_verification = pg.ScatterPlotItem(pxMode=True) self.plot_verification.setZValue(25) @@ -346,12 +346,10 @@ def load_course(self): t1 = t2 # course point - if len(self.config.logger.course.point_longitude) == 0: + if not len(self.config.logger.course.point_longitude): return - t = datetime.datetime.utcnow() - - if self.course_points_plot != None: + if self.course_points_plot is not None: self.plot.removeItem(self.course_points_plot) self.course_points_plot = pg.ScatterPlotItem(pxMode=True, symbol="t", size=12) self.course_points_plot.setZValue(40) @@ -390,11 +388,11 @@ async def update_extra(self): # t = datetime.datetime.utcnow() # display current position - if len(self.location) > 0: + if len(self.location): self.plot.removeItem(self.current_point) self.location.pop() # display center point - if len(self.center_point_location) > 0: + if len(self.center_point_location): self.plot.removeItem(self.center_point) self.center_point_location.pop() @@ -403,11 +401,10 @@ async def update_extra(self): # dummy position if np.isnan(self.gps_values["lon"]) or np.isnan(self.gps_values["lat"]): # recent point(from log or pre_point) / course start / dummy - if len(self.tracks_lon) > 0 and len(self.tracks_lat) > 0: + if len(self.tracks_lon) and len(self.tracks_lat): self.point["pos"] = [self.tracks_lon_pos, self.tracks_lat_pos] - elif ( - len(self.config.logger.course.longitude) > 0 - and len(self.config.logger.course.latitude) > 0 + elif len(self.config.logger.course.longitude) and len( + self.config.logger.course.latitude ): self.point["pos"] = [ self.config.logger.course.longitude[0], @@ -440,7 +437,7 @@ async def update_extra(self): x_move = y_move = 0 if ( self.lock_status - and len(self.config.logger.course.distance) > 0 + and len(self.config.logger.course.distance) and self.gps_values["on_course_status"] ): index = self.gps_sensor.get_index_with_distance_cutoff( @@ -515,7 +512,6 @@ async def update_extra(self): # t = datetime.datetime.utcnow() # set x and y ranges - x_start = x_end = y_start = y_end = np.nan x_start = self.map_pos["x"] - self.map_area["w"] / 2 x_end = x_start + self.map_area["w"] y_start = self.map_pos["y"] - self.map_area["h"] / 2 @@ -558,13 +554,11 @@ async def update_extra(self): def get_track(self): # get track from SQL - lon = [] - lat = [] # not good (input & output) #conversion coordinate (self.tracks_timestamp, lon, lat) = self.config.logger.update_track( self.tracks_timestamp ) - if len(lon) > 0 and len(lat) > 0: + if len(lon) and len(lat): self.tracks_lon_pos = lon[-1] self.tracks_lat_pos = lat[-1] self.tracks_lon = np.append(self.tracks_lon, np.array(lon)) @@ -583,11 +577,10 @@ def reset_course(self): self.course_points_plot, self.instruction, ]: - if p != None: + if p is not None: self.plot.removeItem(p) - p = None - if self.cuesheet_widget != None: + if self.cuesheet_widget is not None: self.cuesheet_widget.reset() def init_course(self): @@ -674,13 +667,13 @@ async def overlay_windmap(self, drawn_main_map, p0, p1): init_time_list = await self.config.network.api.get_scw_list( map_config[map_name], "inittime" ) - if init_time_list != None: + if init_time_list is not None: map_config[map_name]["basetime"] = init_time_list[0]["it"] timeline = await self.config.network.api.get_scw_list( map_config[map_name], "fl" ) - if timeline != None: + if timeline is not None: map_config[map_name]["fl"] = timeline time_str = map_config[map_name]["nowtime"].strftime("%H%M") for tl in map_config[map_name]["fl"]: @@ -808,7 +801,6 @@ async def draw_map_tile_by_overlay( # draw only the necessary tiles w_h = int(tile_size / z_conv_factor) if expand else 0 for keys in add_keys: - imgarray = np.full((tile_size, tile_size, 3), 255, dtype="uint8") x, y = keys[0:2] if not expand else expand_keys[keys][0:2] img_file = self.get_image_file(use_mbtiles, map_name, z_draw, x, y) if not expand: @@ -872,7 +864,8 @@ def init_draw_map(self, map_config, map_name, z, p0, p1, expand, tile_size): tile_y = sorted([t0[1], t1[1]]) return z_draw, z_conv_factor, tile_x, tile_y - def get_tiles_for_drawing(self, tile_x, tile_y, z_conv_factor, expand): + @staticmethod + def get_tiles_for_drawing(tile_x, tile_y, z_conv_factor, expand): tiles = [] for i in range(tile_x[0], tile_x[1] + 1): for j in range(tile_y[0], tile_y[1] + 1): @@ -917,7 +910,7 @@ async def download_tiles(self, tiles, map_config, map_name, z_draw): download_tile.append(tile) # start downloading - if len(download_tile) > 0: + if len(download_tile): if not await self.config.network.download_maptile( map_config, map_name, z_draw, download_tile, additional_download=True ): @@ -973,7 +966,6 @@ def check_tile(self, use_mbtiles, map_name, z_draw, key): return cond def get_image_file(self, use_mbtiles, map_name, z_draw, x, y): - img_file = None if not use_mbtiles: img_file = self.config.get_maptile_filename(map_name, z_draw, x, y) else: @@ -1026,14 +1018,14 @@ async def update_cuesheet_and_instruction( self, x_start, x_end, y_start, y_end, auto_zoom=False ): if ( - len(self.config.logger.course.point_name) == 0 + not len(self.config.logger.course.point_name) or self.config.G_CUESHEET_DISPLAY_NUM == 0 or not self.config.G_COURSE_INDEXING ): return await self.cuesheet_widget.update_extra() - if self.instruction != None: + if self.instruction is not None: self.plot.removeItem(self.instruction) image_src = '' # svg if self.cuesheet_widget.cuesheet[0].name.text() == "Right": @@ -1063,7 +1055,7 @@ async def update_cuesheet_and_instruction( # print(self.zoomlevel, self.cuesheet_widget.cuesheet[0].dist_num, self.auto_zoomlevel_back) if self.cuesheet_widget.cuesheet[0].dist_num < 1000: if ( - self.auto_zoomlevel_back == None + self.auto_zoomlevel_back is None and self.zoomlevel < self.auto_zoomlevel - delta ): self.auto_zoomlevel_back = self.zoomlevel @@ -1071,7 +1063,7 @@ async def update_cuesheet_and_instruction( # print("zoom in", self.auto_zoomlevel_back, self.zoomlevel) else: if ( - self.auto_zoomlevel_back != None + self.auto_zoomlevel_back is not None and self.zoomlevel == self.auto_zoomlevel - delta ): self.zoomlevel = self.auto_zoomlevel_back diff --git a/modules/pyqt/graph/pyqt_value_graph.py b/modules/pyqt/graph/pyqt_value_graph.py index ad07cac9..24033f84 100644 --- a/modules/pyqt/graph/pyqt_value_graph.py +++ b/modules/pyqt/graph/pyqt_value_graph.py @@ -210,12 +210,12 @@ async def update_extra(self): all_nan[key] = False m = [x for x in v[0] if not np.isnan(x)] median = None - if len(m) > 0: + if len(m): median = m[-1] if not all_nan[X]: self.p1.clear() - if median != None: + if median is not None: self.p1.setYRange(-self.g_range, self.g_range) self.p1.addItem(pg.PlotCurveItem(v[X], pen=self.pen1, connect="finite")) @@ -223,7 +223,7 @@ async def update_extra(self): if not all_nan[Y]: self.p2.clear() - if median != None: + if median is not None: self.p2.setYRange(-self.g_range, self.g_range) self.p2.setGeometry(self.p1.vb.sceneBoundingRect()) @@ -234,7 +234,7 @@ async def update_extra(self): if not all_nan[Z]: self.p3.clear() - if median != None: + if median is not None: self.p3.setYRange(-self.g_range, self.g_range) self.p3.setGeometry(self.p1.vb.sceneBoundingRect()) @@ -299,7 +299,7 @@ async def update_extra(self): all_nan[key] = False m = [x for x in v["altitude_graph"] if not np.isnan(x)] median = None - if len(m) > 0: + if len(m): median = m[-1] if not all_nan["altitude_graph"]: @@ -314,7 +314,7 @@ async def update_extra(self): self.y_range = 10 * (int(self.y_range / 10) + 1) self.p1.clear() - if median != None: + if median is not None: self.p1.setYRange(median - self.y_range, median + self.y_range) self.p1.addItem( @@ -324,7 +324,7 @@ async def update_extra(self): if not all_nan["altitude_gps_graph"]: self.p2.clear() - if median != None: + if median is not None: self.p2.setYRange( median - self.y_range + self.y_shift, median + self.y_range + self.y_shift, diff --git a/modules/pyqt/menu/pyqt_adjust_widget.py b/modules/pyqt/menu/pyqt_adjust_widget.py index ef7f81c6..3e1c7c3b 100644 --- a/modules/pyqt/menu/pyqt_adjust_widget.py +++ b/modules/pyqt/menu/pyqt_adjust_widget.py @@ -2,7 +2,7 @@ import PyQt6.QtCore as QtCore import PyQt6.QtWidgets as QtWidgets import PyQt6.QtGui as QtGui -except: +except ImportError: import PyQt5.QtCore as QtCore import PyQt5.QtWidgets as QtWidgets import PyQt5.QtGui as QtGui diff --git a/modules/pyqt/menu/pyqt_course_menu_widget.py b/modules/pyqt/menu/pyqt_course_menu_widget.py index 1b5eecf1..d2b701fc 100644 --- a/modules/pyqt/menu/pyqt_course_menu_widget.py +++ b/modules/pyqt/menu/pyqt_course_menu_widget.py @@ -2,14 +2,14 @@ import PyQt6.QtCore as QtCore import PyQt6.QtWidgets as QtWidgets import PyQt6.QtGui as QtGui -except: +except ImportError: import PyQt5.QtCore as QtCore import PyQt5.QtWidgets as QtWidgets import PyQt5.QtGui as QtGui +import asyncio import os import shutil -import asyncio from qasync import asyncSlot from .pyqt_menu_widget import MenuWidget, ListWidget, ListItemWidget @@ -20,11 +20,11 @@ def setup_menu(self): self.button = {} button_conf = ( # Name(page_name), button_attribute, connected functions, layout - ("Local Storage", "submenu", self.load_local_course), + ("Local Storage", "submenu", self.load_local_courses), ( "Ride with GPS", "submenu", - self.load_rwgps_course, + self.load_rwgps_courses, "./img/rwgps_logo.svg", QtCore.QSize(self.logo_size * 4, self.logo_size), ), @@ -58,18 +58,18 @@ def preprocess(self): self.onoff_course_cancel_button() @asyncSlot() - async def load_local_course(self): - await self.load_course("Local Storage") - await self.parentWidget().widget(self.child_index).list_local_course() + async def load_local_courses(self): + await self.change_course_page("Local Storage") + await self.parentWidget().widget(self.child_index).list_local_courses() @asyncSlot() - async def load_rwgps_course(self): + async def load_rwgps_courses(self): asyncio.gather( + self.change_course_page("Ride with GPS"), self.parentWidget().widget(self.child_index).list_ride_with_gps(reset=True), - self.load_course("Ride with GPS"), ) - async def load_course(self, course_type): + async def change_course_page(self, course_type): self.change_page( self.child_page_name, preprocess=True, reset=True, list_type=course_type ) @@ -78,7 +78,7 @@ def google_directions_api_setting_menu(self): self.change_page("Google Directions API mode", preprocess=True) def onoff_course_cancel_button(self): - if len(self.config.logger.course.distance) == 0: + if not len(self.config.logger.course.distance): self.button["Cancel Course"].disable() else: self.button["Cancel Course"].enable() @@ -213,7 +213,7 @@ async def button_func(self): @asyncSlot() async def change_course_detail_page(self): - if self.selected_item == None: + if self.selected_item is None: return self.change_page( self.child_page_name, @@ -225,38 +225,36 @@ async def change_course_detail_page(self): def preprocess_extra(self): self.page_name_label.setText(self.list_type) - async def list_local_course(self): - course = self.config.logger.course.get_courses() - for c in course: + async def list_local_courses(self): + courses = self.config.logger.course.get_courses() + for c in courses: course_item = CourseListItemWidget(self, self.config, self.list_type) course_item.set_info(**c) self.add_list_item(course_item) async def list_ride_with_gps(self, add=False, reset=False): - course = await self.config.network.api.get_ridewithgps_route(add, reset) - if course == None: + courses = await self.config.network.api.get_ridewithgps_route(add, reset) + if courses is None: return - for c in reversed(course): + for c in reversed(courses): course_item = CourseListItemWidget(self, self.config, self.list_type) course_item.set_info(**c) self.add_list_item(course_item) def set_course(self, course_file=None): - if self.selected_item == None: + if self.selected_item is None: return # from Local Storage (self.list) - if course_file == None: - self.course_file = ( - self.config.G_COURSE_DIR + self.selected_item.list_info["id"] - ) + if course_file is None: + self.course_file = self.selected_item.list_info["path"] # from Ride with GPS (CourseDetailWidget) else: self.course_file = course_file # exist course: cancel and set new course - if len(self.config.logger.course.distance) > 0: + if len(self.config.logger.course.distance): self.config.gui.show_dialog( self.cancel_and_set_new_course, "Replace this course?" ) @@ -417,7 +415,7 @@ def preprocess(self, course_info): self.elevation_label.setText("{:.0f}m up".format(course_info["elevation_gain"])) self.locality_label.setText(self.address_format.format(**course_info)) - self.list_id = course_info["id"] + self.list_id = course_info["name"] self.timer.start(self.config.G_DRAW_INTERVAL) @@ -441,21 +439,21 @@ async def update_display(self): # sequentially draw with download # 1st download check if ( - self.privacy_code == None + self.privacy_code is None and self.config.network.api.check_ridewithgps_files(self.list_id, "1st") ): self.draw_images(draw_map_image=True, draw_profile_image=False) self.privacy_code = self.config.logger.course.get_ridewithgps_privacycode( self.list_id ) - if self.privacy_code != None: + if self.privacy_code is not None: # download files with privacy code (2nd download) await self.config.network.api.get_ridewithgps_files_with_privacy_code( self.list_id, self.privacy_code ) # 2nd download with privacy_code check elif ( - self.privacy_code != None + self.privacy_code is not None and self.config.network.api.check_ridewithgps_files(self.list_id, "2nd") ): self.draw_images(draw_map_image=False, draw_profile_image=True) @@ -464,7 +462,7 @@ async def update_display(self): def check_all_image_and_draw(self): # if all files exists, reload images and buttons, stop timer and exit - if not self.all_downloaded and self.config.network != None: + if not self.all_downloaded and self.config.network is not None: self.all_downloaded = self.config.network.api.check_ridewithgps_files( self.list_id, "ALL" ) @@ -487,7 +485,7 @@ def set_course(self): ) def draw_images(self, draw_map_image=True, draw_profile_image=True): - if self.list_id == None: + if self.list_id is None: return False if draw_map_image: @@ -495,7 +493,7 @@ def draw_images(self, draw_map_image=True, draw_profile_image=True): self.config.G_RIDEWITHGPS_API["URL_ROUTE_DOWNLOAD_DIR"] + "preview-{route_id}.png" ).format(route_id=self.list_id) - if self.map_image_size == None: + if self.map_image_size is None: # self.map_image_size = Image.open(filename).size self.map_image_size = QtGui.QImage(filename).size() if self.map_image_size.width() == 0: @@ -512,7 +510,7 @@ def draw_images(self, draw_map_image=True, draw_profile_image=True): self.config.G_RIDEWITHGPS_API["URL_ROUTE_DOWNLOAD_DIR"] + "elevation_profile-{route_id}.jpg" ).format(route_id=self.list_id) - if self.profile_image_size == None: + if self.profile_image_size is None: # self.profile_image_size = Image.open(filename).size self.profile_image_size = QtGui.QImage(filename).size() if self.profile_image_size.width() == 0: diff --git a/modules/pyqt/menu/pyqt_debug_widget.py b/modules/pyqt/menu/pyqt_debug_widget.py deleted file mode 100644 index 64956beb..00000000 --- a/modules/pyqt/menu/pyqt_debug_widget.py +++ /dev/null @@ -1,56 +0,0 @@ -import os - -USE_PYQT6 = False -try: - import PyQt6.QtCore as QtCore - import PyQt6.QtWidgets as QtWidgets - - USE_PYQT6 = True -except: - import PyQt5.QtCore as QtCore - import PyQt5.QtWidgets as QtWidgets - import PyQt5.QtGui as QtGui - -from .pyqt_menu_widget import MenuWidget - -################################## -# debug widgets -################################## - - -class DebugLogViewerWidget(MenuWidget): - def setup_menu(self): - self.menu = QtWidgets.QWidget() - self.back_index_key = "menu" - - self.menu_layout = QtWidgets.QVBoxLayout() - self.menu_layout.setContentsMargins(0, 0, 0, 0) - self.menu_layout.setSpacing(0) - - # self.scroll_area = QtWidgets.QScrollArea() - # self.scroll_area.setWidgetResizable(True) - try: - self.editor = QtWidgets.QTextEdit() - except: - # for old Qt (5.11.3 buster PyQt5 Package) - QtGui.QTextEdit() - self.editor.setReadOnly(True) - self.editor.setLineWrapMode( - QtWidgets.QTextEdit.LineWrapMode.NoWrap - ) if USE_PYQT6 else self.editor.setLineWrapMode(0) - # self.editor.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) - # self.editor.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) - # QtWidgets.QScroller.grabGesture(self, QtWidgets.QScroller.LeftMouseButtonGesture) - # self.scroll_area.setWidget(self.editor) if USE_PYQT6 else self.menu_layout.addWidget(self.editor) - # self.menu_layout.addWidget(self.scroll_area) - self.menu_layout.addWidget(self.editor) - - self.menu.setLayout(self.menu_layout) - - def update_display(self): - debug_log = "log/debug.txt" - if not os.path.exists(debug_log): - return - f = open(debug_log) - self.editor.setText(f.read()) - f.close() diff --git a/modules/pyqt/menu/pyqt_map_menu_widget.py b/modules/pyqt/menu/pyqt_map_menu_widget.py index a95f8509..f6812041 100644 --- a/modules/pyqt/menu/pyqt_map_menu_widget.py +++ b/modules/pyqt/menu/pyqt_map_menu_widget.py @@ -1,16 +1,15 @@ import asyncio -import _ctypes try: import PyQt6.QtCore as QtCore import PyQt6.QtWidgets as QtWidgets import PyQt6.QtGui as QtGui -except: +except ImportError: import PyQt5.QtCore as QtCore import PyQt5.QtWidgets as QtWidgets import PyQt5.QtGui as QtGui -from .pyqt_menu_widget import MenuWidget, ListWidget, ListItemWidget +from .pyqt_menu_widget import MenuWidget, ListWidget class MapMenuWidget(MenuWidget): @@ -93,7 +92,7 @@ def onoff_map(self, overlay_type, change, is_use): self.button[list_key].onoff_button(status) # OFF: remove overlay - if self.config.gui.map_widget != None: + if self.config.gui.map_widget is not None: self.config.gui.map_widget.reset_map() def select_heatmap(self): diff --git a/modules/pyqt/menu/pyqt_menu_widget.py b/modules/pyqt/menu/pyqt_menu_widget.py index e8d330d1..8988ebf0 100644 --- a/modules/pyqt/menu/pyqt_menu_widget.py +++ b/modules/pyqt/menu/pyqt_menu_widget.py @@ -2,7 +2,7 @@ import PyQt6.QtCore as QtCore import PyQt6.QtWidgets as QtWidgets import PyQt6.QtGui as QtGui -except: +except ImportError: import PyQt5.QtCore as QtCore import PyQt5.QtWidgets as QtWidgets import PyQt5.QtGui as QtGui @@ -116,14 +116,12 @@ def make_menu_layout(self, qt_layout): def add_buttons(self, buttons, back_connect=True): n = len(buttons) - layout_type = None if n <= 4: layout_type = QtWidgets.QVBoxLayout else: layout_type = QtWidgets.QGridLayout - if layout_type != None: - self.make_menu_layout(layout_type) + self.make_menu_layout(layout_type) i = 0 for b in buttons: @@ -141,7 +139,7 @@ def add_buttons(self, buttons, back_connect=True): else: self.button[b[0]].set_null_icon() - if b[2] != None: + if b[2] is not None: self.button[b[0]].clicked.connect(b[2]) else: self.button[b[0]].setEnabled(False) @@ -183,7 +181,7 @@ def connect_back_button(self): def back(self): index = 0 if ( - self.back_index_key != None + self.back_index_key is not None and self.back_index_key in self.config.gui.gui_config.G_GUI_INDEX ): index = self.config.gui.gui_config.G_GUI_INDEX[self.back_index_key] @@ -301,7 +299,7 @@ def set_service_icon(self, label_img, qsize): def set_submenu_icon(self, label_img=None, qsize=None): self.button_type = "submenu" - if label_img != None and qsize != None: + if label_img is not None and qsize is not None: self.set_service_icon(label_img, qsize) self.set_icon_with_size() @@ -524,7 +522,7 @@ async def button_func_extra(self): def changed_item(self): # item is QListWidgetItem item = self.list.selectedItems() - if len(item) > 0: + if len(item): self.selected_item = self.list.itemWidget(item[0]) def resizeEvent(self, event): @@ -556,7 +554,7 @@ def preprocess_extra(self): for i, k in enumerate(self.settings): if k == default_value: default_index = i - if default_index != None: + if default_index is not None: self.list.setCurrentRow(default_index) self.list.itemWidget(self.list.currentItem()).setFocus() @@ -565,7 +563,7 @@ def get_default_value(self): def add_list_item(self, item): list_item = QtWidgets.QListWidgetItem(self.list) - if self.size_hint != None: + if self.size_hint is not None: list_item.setSizeHint(self.size_hint) self.list.setItemWidget(list_item, item) diff --git a/modules/pyqt/menu/pyqt_profile_widget.py b/modules/pyqt/menu/pyqt_profile_widget.py index abdae075..c476fd00 100644 --- a/modules/pyqt/menu/pyqt_profile_widget.py +++ b/modules/pyqt/menu/pyqt_profile_widget.py @@ -2,7 +2,7 @@ import PyQt6.QtCore as QtCore import PyQt6.QtWidgets as QtWidgets import PyQt6.QtGui as QtGui -except: +except ImportError: import PyQt5.QtCore as QtCore import PyQt5.QtWidgets as QtWidgets import PyQt5.QtGui as QtGui diff --git a/modules/pyqt/menu/pyqt_sensor_menu_widget.py b/modules/pyqt/menu/pyqt_sensor_menu_widget.py index a50854b5..0bbda2f9 100644 --- a/modules/pyqt/menu/pyqt_sensor_menu_widget.py +++ b/modules/pyqt/menu/pyqt_sensor_menu_widget.py @@ -2,7 +2,7 @@ import PyQt6.QtCore as QtCore import PyQt6.QtWidgets as QtWidgets import PyQt6.QtGui as QtGui -except: +except ImportError: import PyQt5.QtCore as QtCore import PyQt5.QtWidgets as QtWidgets import PyQt5.QtGui as QtGui @@ -125,7 +125,7 @@ async def button_func_extra(self): print( "connect {}: {}".format(self.list_type, self.selected_item.list_info["id"]) ) - if self.selected_item == None: + if self.selected_item is None: return ant_id = int(self.selected_item.list_info["id"]) self.config.logger.sensor.sensor_ant.connect_ant_sensor( diff --git a/modules/pyqt/menu/pyqt_system_menu_widget.py b/modules/pyqt/menu/pyqt_system_menu_widget.py index f43fc2ac..98ce9dc4 100644 --- a/modules/pyqt/menu/pyqt_system_menu_widget.py +++ b/modules/pyqt/menu/pyqt_system_menu_widget.py @@ -1,14 +1,10 @@ import os -import asyncio -import datetime -import re -import json try: import PyQt6.QtCore as QtCore import PyQt6.QtWidgets as QtWidgets import PyQt6.QtGui as QtGui -except: +except ImportError: import PyQt5.QtCore as QtCore import PyQt5.QtWidgets as QtWidgets import PyQt5.QtGui as QtGui @@ -75,10 +71,10 @@ def setup_menu(self): self.bt_page_name = "BT Tethering" self.bt_index = self.config.gui.gui_config.G_GUI_INDEX[self.bt_page_name] - if self.config.bt_pan == None or len(self.config.G_BT_ADDRESS) == 0: + if self.config.bt_pan is None or not len(self.config.G_BT_ADDRESS): self.button["BT Tethering"].disable() - if self.config.ble_uart == None: + if self.config.ble_uart is None: self.button["Gadgetbridge"].disable() self.button["Get Location"].disable() diff --git a/modules/pyqt/pyqt_button_box_widget.py b/modules/pyqt/pyqt_button_box_widget.py index b31595e2..f1e6f45a 100644 --- a/modules/pyqt/pyqt_button_box_widget.py +++ b/modules/pyqt/pyqt_button_box_widget.py @@ -5,7 +5,7 @@ import PyQt6.QtGui as QtGui USE_PYQT6 = True -except: +except ImportError: import PyQt5.QtCore as QtCore import PyQt5.QtWidgets as QtWidgets import PyQt5.QtGui as QtGui diff --git a/modules/pyqt/pyqt_cuesheet_widget.py b/modules/pyqt/pyqt_cuesheet_widget.py index f5496ed2..c6c72d49 100644 --- a/modules/pyqt/pyqt_cuesheet_widget.py +++ b/modules/pyqt/pyqt_cuesheet_widget.py @@ -2,7 +2,7 @@ import PyQt6.QtCore as QtCore import PyQt6.QtWidgets as QtWidgets import PyQt6.QtGui as QtGui -except: +except ImportError: import PyQt5.QtCore as QtCore import PyQt5.QtWidgets as QtWidgets import PyQt5.QtGui as QtGui @@ -61,7 +61,6 @@ def __init__(self, parent, config): self.dist = QtWidgets.QLabel() self.dist.setWordWrap(False) self.dist_num = 0 - # self.name = QtWidgets.QLabel() self.name = MarqueeLabel(self.config) self.name.setWordWrap(False) @@ -128,11 +127,9 @@ def reset(self): self.cuesheet[i].name.setText("") def resizeEvent(self, event): - # w = self.size().width() h = self.size().height() self.set_font_size(h) for i in self.cuesheet: - # i.update_font_size(int(self.font_size*0.66)) i.update_font_size(int(self.font_size)) # for 3 rows def set_font_size(self, length): @@ -140,7 +137,7 @@ def set_font_size(self, length): async def update_extra(self): if ( - len(self.config.logger.course.point_distance) == 0 + not len(self.config.logger.course.point_distance) or self.config.G_CUESHEET_DISPLAY_NUM == 0 ): return @@ -163,6 +160,5 @@ async def update_extra(self): if dist > 1000: text = "{0:4.1f}km ".format(dist / 1000) self.cuesheet[j].dist.setText(text) - # text = self.config.logger.course.point_name[cp_i+j] text = self.config.logger.course.point_type[cp_i + j] self.cuesheet[j].name.setText(text) diff --git a/modules/pyqt/pyqt_graph_debug.py b/modules/pyqt/pyqt_graph_debug.py index aeecdac8..19d0e640 100644 --- a/modules/pyqt/pyqt_graph_debug.py +++ b/modules/pyqt/pyqt_graph_debug.py @@ -72,12 +72,12 @@ def update_extra(self): all_nan[key] = False m = [x for x in v[0] if not np.isnan(x)] median = None - if len(m) > 0: + if len(m): median = m[-1] if not all_nan[X]: self.p1.clear() - if median != None: + if median is not None: self.p1.setYRange(-self.g_range, self.g_range) self.p1.addItem(pg.PlotCurveItem(v[X], pen=self.pen1, connect="finite")) @@ -85,7 +85,7 @@ def update_extra(self): if not all_nan[Y]: self.p2.clear() - if median != None: + if median is not None: self.p2.setYRange(-self.g_range, self.g_range) self.p2.setGeometry(self.p1.vb.sceneBoundingRect()) @@ -96,7 +96,7 @@ def update_extra(self): if not all_nan[Z]: self.p3.clear() - if median != None: + if median is not None: self.p3.setYRange(-self.g_range, self.g_range) self.p3.setGeometry(self.p1.vb.sceneBoundingRect()) @@ -161,7 +161,7 @@ def update_extra(self): all_nan[key] = False m = [x for x in v["altitude_graph"] if not np.isnan(x)] median = None - if len(m) > 0: + if len(m): median = m[-1] if not all_nan["altitude_graph"]: @@ -176,7 +176,7 @@ def update_extra(self): self.y_range = 10 * (int(self.y_range / 10) + 1) self.p1.clear() - if median != None: + if median is not None: self.p1.setYRange(median - self.y_range, median + self.y_range) self.p1.addItem( @@ -186,7 +186,7 @@ def update_extra(self): if not all_nan["altitude_gps_graph"]: self.p2.clear() - if median != None: + if median is not None: self.p2.setYRange( median - self.y_range + self.y_shift, median + self.y_range + self.y_shift, diff --git a/modules/pyqt/pyqt_item.py b/modules/pyqt/pyqt_item.py index a50f5cbf..61bb314e 100644 --- a/modules/pyqt/pyqt_item.py +++ b/modules/pyqt/pyqt_item.py @@ -4,7 +4,7 @@ import PyQt6.QtCore as QtCore import PyQt6.QtGui as QtGui import PyQt6.QtWidgets as QtWidgets -except: +except ImportError: import PyQt5.QtCore as QtCore import PyQt5.QtGui as QtGui import PyQt5.QtWidgets as QtWidgets @@ -45,10 +45,10 @@ def set_init_value(self, config, name, font_size, bottom_flag, right_flag): self.addWidget(self.value) bottom_border_width = "1px" - if bottom_flag == True: + if bottom_flag: bottom_border_width = "0px" right_border_width = "1px" - if right_flag == True: + if right_flag: right_border_width = "0px" self.label.setStyleSheet( @@ -73,7 +73,7 @@ def set_init_value(self, config, name, font_size, bottom_flag, right_flag): self.update_value(np.nan) def update_value(self, value): - if value == None: + if value is None: self.value.setText("-") elif isinstance(value, str): self.value.setText(value) diff --git a/modules/pyqt/pyqt_screen_widget.py b/modules/pyqt/pyqt_screen_widget.py index b0d567c5..7d6b01bb 100644 --- a/modules/pyqt/pyqt_screen_widget.py +++ b/modules/pyqt/pyqt_screen_widget.py @@ -3,7 +3,7 @@ try: import PyQt6.QtCore as QtCore import PyQt6.QtWidgets as QtWidgets -except: +except ImportError: import PyQt5.QtCore as QtCore import PyQt5.QtWidgets as QtWidgets @@ -36,7 +36,6 @@ def __init__(self, parent, config): self.setup_ui() def resizeEvent(self, event): - # w = self.size().width() h = self.size().height() self.set_font_size(h) for i in self.items: @@ -155,7 +154,6 @@ async def update_display(self): return for item in self.items: - # item.update_value(eval(self.config.gui.gui_config.[item.name][1])) try: item.update_value( eval(self.config.gui.gui_config.G_ITEM_DEF[item.name][1]) diff --git a/modules/sensor/ant/ant_device.py b/modules/sensor/ant/ant_device.py index bde4db96..b361489e 100644 --- a/modules/sensor/ant/ant_device.py +++ b/modules/sensor/ant/ant_device.py @@ -50,15 +50,18 @@ class ANT_Device: } ant_idle_interval = {"NORMAL": 0.20, "QUICK": 0.01, "SCAN": 0.20} - def __init__(self, node=None, config=None, values={}, name=""): + def __init__(self, node=None, config=None, values=None, name=""): self.node = node self.config = config self.name = name - self.values = values + if values is None: + self.values = {} + else: + self.values = values self.add_struct_pattern() self.init_value() - if node == None: + if node is None: return # for dummy device self.make_channel(self.ant_config["channel_type"]) self.init_extra() @@ -95,7 +98,7 @@ def reset_value(self): pass def make_channel(self, c_type, ext_assign=None): - if self.config.G_ANT["STATUS"] and self.channel == None: + if self.config.G_ANT["STATUS"] and self.channel is None: self.channel = self.node.new_channel(c_type, ext_assign=ext_assign) print("{} ".format(self.name), end="") self.channel.on_broadcast_data = self.on_data @@ -214,7 +217,8 @@ def setCommonPage82(self, data, values): values["battery_status"] = self.battery_status[(data[1] >> 4) & 0b111] values["battery_voltage"] = round(float(data[1] & 0b1111) + data[0] / 256, 2) - def print_spike(self, device_str, val, pre_val, delta, delta_t): + @staticmethod + def print_spike(device_str, val, pre_val, delta, delta_t): print( "ANT+ {0} spike: {1},".format( device_str, datetime.datetime.now().strftime("%Y%m%d %H:%M:%S") diff --git a/modules/sensor/ant/ant_device_light.py b/modules/sensor/ant/ant_device_light.py index 8a6dd197..aa8d7cc7 100644 --- a/modules/sensor/ant/ant_device_light.py +++ b/modules/sensor/ant/ant_device_light.py @@ -79,8 +79,8 @@ def get_mode(self, m): def init_after_connect(self): if ( - self.values["pre_lgt_state"] == None - and self.values["lgt_state"] == None + self.values["pre_lgt_state"] is None + and self.values["lgt_state"] is None and self.ant_state in ["connect_ant_sensor"] ): self.send_connect_light() @@ -91,7 +91,7 @@ def on_data(self, data): seq_no = data[4] # print("###", mode, self.values['lgt_state'], self.page_34_count, seq_no, (datetime.datetime.now() - self.values['last_changed_timestamp']).total_seconds()) if ( - self.values["lgt_state"] != None + self.values["lgt_state"] is not None and seq_no != self.page_34_count and ( datetime.datetime.now() - self.values["last_changed_timestamp"] @@ -187,7 +187,7 @@ def send_light_setting_steady_mid(self, auto=False): def check_mode(self): if ( - self.values["lgt_state"] != None + self.values["lgt_state"] is not None and self.values["lgt_state"] != self.values["pre_lgt_state"] ): print( diff --git a/modules/sensor/ant/ant_device_power.py b/modules/sensor/ant/ant_device_power.py index 4f463ba1..5e9c014b 100644 --- a/modules/sensor/ant/ant_device_power.py +++ b/modules/sensor/ant/ant_device_power.py @@ -145,7 +145,7 @@ def on_data_power_0x10(self, data, power_values, pre_values, values): values["cadence"] = cadence if ( self.config.G_MANUAL_STATUS == "START" - and values["on_data_timestamp"] != None + and values["on_data_timestamp"] is not None ): # unit: j values["accumulated_power"] += pwr * round( @@ -164,7 +164,7 @@ def on_data_power_0x10(self, data, power_values, pre_values, values): else: self.print_spike("Power(16)", pwr, values["power"], delta, delta_t) elif delta[0] == 0 and delta[1] == 0: - # if values['on_data_timestamp'] != None and delta_t >= self.stop_cutoff: + # if values['on_data_timestamp'] is not None and delta_t >= self.stop_cutoff: values["power"] = 0 values["power_16_simple"] = 0 values["cadence"] = 0 @@ -185,7 +185,7 @@ def on_data_power_0x10(self, data, power_values, pre_values, values): self.config.setting.set_config_pickle("ant+_power_values_16", power_values[1]) def on_data_power_0x11(self, data, power_values, pre_values, values): - # (page), evt_count, wheel_ticks, x, wheel period(2byte), accumulatd power(2byte) + # (page), evt_count, wheel_ticks, x, wheel period(2byte), accumulated power(2byte) ( power_values[2], power_values[3], @@ -255,7 +255,7 @@ def on_data_power_0x11(self, data, power_values, pre_values, values): else: self.print_spike("Speed(17)", spd, values["speed"], delta, delta_t) elif delta[0] == 0 and delta[1] == 0 and delta[2] == 0: - # if values['on_data_timestamp'] != None and delta_t >= self.stop_cutoff: + # if values['on_data_timestamp'] is not None and delta_t >= self.stop_cutoff: values["power"] = 0 values["speed"] = 0 else: diff --git a/modules/sensor/ant/ant_device_speed_cadence.py b/modules/sensor/ant/ant_device_speed_cadence.py index b93db357..f9d57be0 100644 --- a/modules/sensor/ant/ant_device_speed_cadence.py +++ b/modules/sensor/ant/ant_device_speed_cadence.py @@ -15,7 +15,6 @@ class ANT_Device_Speed_Cadence(ant_device.ANT_Device): sc_values = [] # cad_time, cad, speed_time, speed pre_values = [] # cad_time, cad, speed_time, speed delta = [] # cad_time, cad, speed_time, speed - pre_values = [] # cad_time, cad, speed_time, speed elements = ("speed", "cadence", "distance") pickle_key = "ant+_sc_values" @@ -90,7 +89,7 @@ def on_data(self, data): "Speed(S&C)", spd, self.values["speed"], self.delta, [] ) elif self.delta[2] == 0 and self.delta[3] == 0: - # if self.values['on_data_timestamp'] != None and (t - self.values['on_data_timestamp']).total_seconds() >= self.stop_cutoff: + # if self.values['on_data_timestamp'] is not None and (t - self.values['on_data_timestamp']).total_seconds() >= self.stop_cutoff: self.values["speed"] = 0 else: print( @@ -109,7 +108,7 @@ def on_data(self, data): # refresh timestamp called from sensor_core self.values["timestamp"] = t elif self.delta[0] == 0 and self.delta[1] == 0: - # if self.values['on_data_timestamp'] != None and (t - self.values['on_data_timestamp']).total_seconds() >= self.stop_cutoff: + # if self.values['on_data_timestamp'] is not None and (t - self.values['on_data_timestamp']).total_seconds() >= self.stop_cutoff: self.values["cadence"] = 0 else: print( @@ -186,7 +185,7 @@ def on_data(self, data): self.elements[0], val, self.values[self.elements[0]], self.delta, [] ) elif self.delta[0] == 0 and self.delta[1] == 0: - # if self.values['on_data_timestamp'] != None and (t - self.values['on_data_timestamp']).total_seconds() >= self.stop_cutoff: + # if self.values['on_data_timestamp'] is not None and (t - self.values['on_data_timestamp']).total_seconds() >= self.stop_cutoff: self.values[self.elements[0]] = 0 else: print( diff --git a/modules/sensor/i2c/MMC5983MA.py b/modules/sensor/i2c/MMC5983MA.py index 32ad95d4..0b26f40a 100644 --- a/modules/sensor/i2c/MMC5983MA.py +++ b/modules/sensor/i2c/MMC5983MA.py @@ -1,13 +1,12 @@ import time import struct -import math import numpy as np try: # run from top directory (pizero_bikecomputer) from . import i2c -except: +except ImportError: # directly run this program import i2c diff --git a/modules/sensor/i2c/MS5637.py b/modules/sensor/i2c/MS5637.py index 4c843464..b0f17709 100644 --- a/modules/sensor/i2c/MS5637.py +++ b/modules/sensor/i2c/MS5637.py @@ -1,10 +1,9 @@ import time -import struct try: # run from top directory (pizero_bikecomputer) from . import i2c -except: +except ImportError: # directly run this program import i2c @@ -106,10 +105,6 @@ def read(self): OFF = self.C2 * 131072 + (self.C4 * dT) / 64 SENS = self.C1 * 65536 + (self.C3 * dT) / 128 - T2 = 0 - OFF2 = 0 - SENS2 = 0 - if TEMP >= 2000: T2 = 5 * dT * dT / 274877906944 OFF2 = 0 diff --git a/modules/sensor/i2c/button_shim.py b/modules/sensor/i2c/button_shim.py index 04985b16..0f6010a3 100644 --- a/modules/sensor/i2c/button_shim.py +++ b/modules/sensor/i2c/button_shim.py @@ -79,7 +79,8 @@ def press_E(self): def press_E_LONG(self): self.press_button("E", 1) - def set_pixel(self, r, g, b): + @staticmethod + def set_pixel(r, g, b): buttonshim.set_pixel(r, g, b) # Button A diff --git a/modules/sensor/i2c/i2c.py b/modules/sensor/i2c/i2c.py index eb78ab7b..0916d41f 100644 --- a/modules/sensor/i2c/i2c.py +++ b/modules/sensor/i2c/i2c.py @@ -1,7 +1,7 @@ -import smbus import time import numpy as np +import smbus class i2c: @@ -33,11 +33,11 @@ def __init__(self): self.init_sensor() @classmethod - def test(self): + def test(cls): try: bus = smbus.SMBus(1) - for v in self.TEST_VALUE: - if bus.read_byte_data(self.SENSOR_ADDRESS, self.TEST_ADDRESS) == v: + for v in cls.TEST_VALUE: + if bus.read_byte_data(cls.SENSOR_ADDRESS, cls.TEST_ADDRESS) == v: return True return False except: diff --git a/modules/sensor/kalman_filter.py b/modules/sensor/kalman_filter.py index 97a8561c..6c1e580c 100644 --- a/modules/sensor/kalman_filter.py +++ b/modules/sensor/kalman_filter.py @@ -1,13 +1,10 @@ # simplify filterpy -import datetime import sys from math import log from copy import deepcopy -from numpy import dot, zeros, eye, isscalar, linalg, array, atleast_2d, loadtxt, matrix - -# from scipy.linalg import block_diag +from numpy import dot, zeros, eye, isscalar, linalg, array, atleast_2d def reshape_z(z, dim_z, ndim): @@ -244,7 +241,7 @@ def __init__(self, dim_x, dim_z, dim_u=0): self.x_post = self.x.copy() self.P_post = self.P.copy() - # Only computed only if requested via property + # Only computed if requested via property self._log_likelihood = log(sys.float_info.min) self._likelihood = sys.float_info.min self._mahalanobis = None diff --git a/modules/sensor/sensor.py b/modules/sensor/sensor.py index 7e48cbaf..9f00570f 100644 --- a/modules/sensor/sensor.py +++ b/modules/sensor/sensor.py @@ -1,4 +1,3 @@ -import time import datetime import asyncio diff --git a/modules/sensor/sensor_ant.py b/modules/sensor/sensor_ant.py index 81646541..19694fd0 100644 --- a/modules/sensor/sensor_ant.py +++ b/modules/sensor/sensor_ant.py @@ -29,7 +29,7 @@ # device test _driver = find_driver() _SENSOR_ANT = True -except: +except ImportError: pass f.close() sys.stdout = sys.__stdout__ diff --git a/modules/sensor/sensor_gpio.py b/modules/sensor/sensor_gpio.py index 628207f3..2ffde976 100644 --- a/modules/sensor/sensor_gpio.py +++ b/modules/sensor/sensor_gpio.py @@ -9,7 +9,7 @@ import RPi.GPIO as GPIO _SENSOR_RPiGPIO = True -except: +except ImportError: pass if _SENSOR_RPiGPIO: diff --git a/modules/sensor/sensor_gps.py b/modules/sensor/sensor_gps.py index 76882e0e..7e4f2219 100644 --- a/modules/sensor/sensor_gps.py +++ b/modules/sensor/sensor_gps.py @@ -14,7 +14,7 @@ from dateutil import parser _SENSOR_GPS_BASIC = True -except: +except ImportError: pass _SENSOR_GPS_I2C = False @@ -25,7 +25,7 @@ _sensor_i2c_gps = pa1010d.PA1010D() _sensor_i2c_gps.read_sentence(timeout=1) _SENSOR_GPS_I2C = True -except: +except ImportError: pass _SENSOR_GPS_GPSD = False @@ -180,8 +180,8 @@ async def dummy_update(self): while not self.config.G_QUIT: await self.sleep() - if self.config.logger == None or ( - len(self.config.logger.course.latitude) == 0 + if self.config.logger is None or ( + not len(self.config.logger.course.latitude) and self.config.logger.position_log.shape[0] == 0 ): continue @@ -205,10 +205,10 @@ async def dummy_update(self): self.values["lon"] = self.config.logger.position_log[course_i][1] self.values["distance"] = self.config.logger.position_log[course_i][2] self.values["track"] = self.config.logger.position_log[course_i][3] - if self.values["lat"] == None or self.values["lon"] == None: + if self.values["lat"] is None or self.values["lon"] is None: self.values["lat"] = np.nan self.values["lon"] = np.nan - if self.values["track"] == None: + if self.values["track"] is None: self.values["track"] = self.values["pre_track"] if course_i == pre_course_i: course_i += 1 * log_speed @@ -313,7 +313,10 @@ async def update_i2c(self): lat = self.config.G_GPS_NULLVALUE lon = self.config.G_GPS_NULLVALUE timestamp = self.config.G_GPS_NULLVALUE - if g.data["mode_fix_type"] != None and int(g.data["mode_fix_type"]) > 1: + if ( + g.data["mode_fix_type"] is not None + and int(g.data["mode_fix_type"]) > 1 + ): lat = g.data["latitude"] lon = g.data["longitude"] if g.data["timestamp"] != self.config.G_GPS_NULLVALUE: @@ -409,7 +412,7 @@ async def get_GPS_basic_values(self, lat, lon, alt, speed, track, mode, error, d self.values["mode"] = mode # err(GPSd only) - if error != None: + if error is not None: for i, key in enumerate(["epx", "epy", "epv"]): if error[i] != self.config.G_GPS_NULLVALUE: self.values[key] = error[i] @@ -445,7 +448,7 @@ async def get_GPS_basic_values(self, lat, lon, alt, speed, track, mode, error, d ): valid_pos = False - if error != None: + if error is not None: if np.any( np.isnan([self.values["epx"], self.values["epy"], self.values["epv"]]) ) or np.any( @@ -538,8 +541,8 @@ async def get_GPS_basic_values(self, lat, lon, alt, speed, track, mode, error, d if ( not self.is_altitude_modified and self.values["on_course_status"] - and self.config.logger != None - and len(self.config.logger.course.altitude) > 0 + and self.config.logger is not None + and len(self.config.logger.course.altitude) ): await self.config.logger.sensor.sensor_i2c.update_sealevel_pa( self.config.logger.course.altitude[self.values["course_index"]] @@ -567,7 +570,7 @@ def get_satellites(self, gs): def get_satellites_adafruit(self, gs): gnum = guse = 0 - if gs == self.config.G_GPS_NULLVALUE or len(gs) == 0: + if gs == self.config.G_GPS_NULLVALUE or not len(gs): return "0/0" for v in gs.values(): gnum += 1 @@ -641,7 +644,7 @@ def get_course_index(self): # don't search # initializing logger - if self.config.logger == None: + if self.config.logger is None: return # no gps value if np.isnan(self.values["lon"]) or np.isnan(self.values["lat"]): @@ -858,7 +861,7 @@ def get_course_index(self): self.config.logger.course.distance[m] * 1000 + dist_diff_course ) - if len(self.config.logger.course.altitude) > 0: + if len(self.config.logger.course.altitude): alt_diff_course = 0 if m + 1 < len(self.config.logger.course.altitude): alt_diff_course = ( @@ -883,7 +886,7 @@ def get_course_index(self): self.values["course_index"] = m - if len(self.config.logger.course.point_distance) > 0: + if len(self.config.logger.course.point_distance): cp_m = np.abs( self.config.logger.course.point_distance - self.values["course_distance"] / 1000 @@ -915,7 +918,7 @@ def get_course_index(self): self.values["on_course_status"] = False def get_index_with_distance_cutoff(self, start, search_range): - if self.config.logger == None or len(self.config.logger.course.distance) == 0: + if self.config.logger is None or not len(self.config.logger.course.distance): return 0 dist_to = self.config.logger.course.distance[start] + search_range @@ -943,5 +946,6 @@ def get_index_with_distance_cutoff(self, start, search_range): return min_index - def hasGPS(self): + @staticmethod + def hasGPS(): return _SENSOR_GPS_GPSD or _SENSOR_GPS_I2C or _SENSOR_GPS_ADAFRUIT_UART diff --git a/modules/sensor/sensor_i2c.py b/modules/sensor/sensor_i2c.py index 634cd3b0..6b3a84f7 100644 --- a/modules/sensor/sensor_i2c.py +++ b/modules/sensor/sensor_i2c.py @@ -12,7 +12,7 @@ import smbus _SENSOR_I2C = True -except: +except ImportError: pass if _SENSOR_I2C: print("I2C ", end="") @@ -22,7 +22,7 @@ from magnetic_field_calculator import MagneticFieldCalculator _SENSOR_MAG_DECLINATION = True -except: +except ImportError: pass # acc @@ -774,7 +774,7 @@ def calc_heading(self, yaw): if ( _SENSOR_MAG_DECLINATION and not self.is_mag_declination_modified - and self.config.logger != None + and self.config.logger is not None and self.config.detect_network() ): v = self.config.logger.sensor.values["GPS"] @@ -795,20 +795,22 @@ def calc_heading(self, yaw): ) self.values["heading_str"] = self.config.get_track_str(self.values["heading"]) - def get_pitch_roll(self, acc): + @staticmethod + def get_pitch_roll(acc): roll = math.atan2(acc[Y], acc[Z]) pitch = math.atan2(-acc[X], (math.sqrt(acc[Y] ** 2 + acc[Z] ** 2))) return pitch, roll - def get_yaw(self, mag, pitch, roll): + @staticmethod + def get_yaw(mag, pitch, roll): cos_p = math.cos(pitch) sin_p = math.sin(pitch) cos_r = math.cos(roll) sin_r = math.sin(roll) tiltcomp_x = mag[X] * cos_p + mag[Z] * sin_p tiltcomp_y = mag[X] * sin_r * sin_p + mag[Y] * cos_r - mag[Z] * sin_r * cos_p - tiltcomp_z = mag[X] * cos_r * sin_p + mag[Y] * sin_r + mag[Z] * cos_r * cos_p + # tiltcomp_z = mag[X] * cos_r * sin_p + mag[Y] * sin_r + mag[Z] * cos_r * cos_p yaw = math.atan2(tiltcomp_y, tiltcomp_x) return yaw @@ -925,7 +927,7 @@ def modified_acc(self): if ( self.motion_sensor["ACC"] and self.motion_sensor["GYRO"] - and self.kfp != None + and self.kfp is not None ): self.kfp.update( math.atan2(-self.values["acc_raw"][X], self.values["acc_raw"][Z]), @@ -1055,7 +1057,10 @@ def calc_altitude(self): self.vspeed_array[0:-1] = self.vspeed_array[1:] # self.vspeed_array[-1] = self.values['altitude'] self.vspeed_array[-1] = self.values["pre_altitude"] - if self.timestamp_array[0] != None and self.timestamp_array[-1] != None: + if ( + self.timestamp_array[0] is not None + and self.timestamp_array[-1] is not None + ): i = 0 time_delta = ( self.timestamp_array[-1] - self.timestamp_array[i] @@ -1071,7 +1076,7 @@ async def update_sealevel_pa(self, alt): or np.isnan(alt) ): return - if self.config.logger == None: + if self.config.logger is None: return # get temperature @@ -1097,13 +1102,12 @@ async def update_sealevel_pa(self, alt): # from OpenWeatherMap API with current point else: - api_data = None v = self.config.logger.sensor.values["GPS"] try: api_data = await self.config.network.api.get_openweathermap_data( v["lon"], v["lat"] ) - if api_data == None: + if api_data is None: raise Exception() if "temp" in api_data["main"]: temperature = api_data["main"]["temp"] - 273.15 @@ -1128,7 +1132,7 @@ async def update_sealevel_pa(self, alt): print("update sealevel pressure") print(" altitude:", alt, "m") print(" pressure:", round(self.values["pressure"], 3), "hPa") - if temperature != None: + if temperature is not None: print(" temp:", round(temperature, 1), "C") print(" sealevel temperature:", round(self.sealevel_temp - 273.15, 1), "C") print(" sealevel pressure:", round(self.sealevel_pa, 3), "hPa") diff --git a/modules/sensor_core.py b/modules/sensor_core.py index e39c8c81..b535146e 100644 --- a/modules/sensor_core.py +++ b/modules/sensor_core.py @@ -9,7 +9,7 @@ import psutil _IMPORT_PSUTIL = True -except: +except ImportError: pass print("detected sensor modules:") @@ -158,11 +158,7 @@ async def integrate(self): # loop control self.wait_time = self.config.G_SENSOR_INTERVAL self.actual_loop_interval = self.config.G_SENSOR_INTERVAL - time_profile = [ - None, - ] - # if True: while not self.config.G_QUIT: await asyncio.sleep(self.wait_time) start_time = datetime.datetime.now() @@ -360,7 +356,7 @@ async def integrate(self): alt_diff_spd["ANT+"] = alt - pre_alt_spd["ANT+"] pre_alt_spd["ANT+"] = alt # dem_altitude - if self.config.G_LOG_ALTITUDE_FROM_DATA_SOUCE: + if self.config.G_LOG_ALTITUDE_FROM_DATA_SOURCE: self.values["integrated"][ "dem_altitude" ] = await self.config.get_altitude_from_tile( @@ -379,7 +375,7 @@ async def integrate(self): self.values["integrated"][key][-self.grade_window_size :] ) # set grade - gr = gl = self.config.G_ANT_NULLVALUE + gl = self.config.G_ANT_NULLVALUE gr = self.config.G_ANT_NULLVALUE x = self.config.G_ANT_NULLVALUE y = diff_sum["alt_diff"] @@ -549,13 +545,13 @@ async def integrate(self): self.config.G_STOPWATCH_STATUS == "STOP" and flag_spd and flag_moving - and self.config.logger != None + and self.config.logger is not None ): self.config.logger.start_and_stop() elif ( self.config.G_STOPWATCH_STATUS == "START" and (not flag_spd or not flag_moving) - and self.config.logger != None + and self.config.logger is not None ): self.config.logger.start_and_stop() @@ -565,7 +561,7 @@ async def integrate(self): if ( (self.config.G_ANT["USE"]["SPD"] or "timestamp" in v["GPS"]) and self.config.G_STOPWATCH_STATUS == "START" - and self.config.logger != None + and self.config.logger is not None ): self.config.logger.start_and_stop() # time.sleep(1) @@ -640,14 +636,14 @@ async def integrate(self): self.wait_time = self.config.G_SENSOR_INTERVAL - d2 self.actual_loop_interval = (d1 + 1) * self.config.G_SENSOR_INTERVAL - def conv_grade(self, gr): + @staticmethod + def conv_grade(gr): g = gr if -1.5 < g < 1.5: g = 0 return int(g) def get_lp_filtered_value(self, value, pre): - o = p = self.config.G_ANT_NULLVALUE # value must be initialized with None if np.isnan(pre): o = value diff --git a/pizero_bikecomputer.py b/pizero_bikecomputer.py index 95812b38..05826754 100755 --- a/pizero_bikecomputer.py +++ b/pizero_bikecomputer.py @@ -2,10 +2,6 @@ import datetime -# import logging -# logging.basicConfig(level=logging.DEBUG) -# logging.basicConfig(filename='example.log', level=logging.DEBUG) - def main(): print() @@ -40,10 +36,9 @@ def main(): t1 = t2 if config.G_GUI_MODE == "PyQt": from modules import gui_pyqt - elif config.G_GUI_MODE == "QML": - from modules import gui_qml - elif config.G_GUI_MODE == "Kivy": - from modules import gui_kivy + else: + raise ValueError(f"{config.G_GUI_MODE} mode not supported") + t2 = datetime.datetime.now() time_profile.append((t2 - t1).total_seconds()) @@ -67,14 +62,9 @@ def main(): print() print("########## INITIALIZE END ##########") config.boot_time += sum(time_profile) - # return if config.G_GUI_MODE == "PyQt": - gui = gui_pyqt.GUI_PyQt(config) - elif config.G_GUI_MODE == "QML": - gui = gui_qml.GUI_QML(config) - elif config.G_GUI_MODE == "Kivy": - gui = gui_kivy.GUI_Kivy(config) + gui_pyqt.GUI_PyQt(config) if __name__ == "__main__": diff --git a/scripts/set_timezone.py b/scripts/set_timezone.py index 8c777452..9ebb2b46 100755 --- a/scripts/set_timezone.py +++ b/scripts/set_timezone.py @@ -28,13 +28,13 @@ try: tz_str = tz.timezone_at(lng=lon, lat=lat) - if tz_str == None: + if tz_str is None: # tz_str = tz.certain_timezone_at(lng=lon, lat=lat) tz_str = tz.closest_timezone_at(lng=lon, lat=lat) print(tz_str) - if tz_str != None: + if tz_str is not None: cmd = [ "sudo", "timedatectl",