From 42b715575cb72c06880f9a85eb8692bfbc64d71e Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Sun, 1 Oct 2023 22:13:46 +0200 Subject: [PATCH] Changed CLI threads polling into blocking reads, to reduce CPU usage --- CHANGELOG.md | 1 + software/script/chameleon_com.py | 14 +++++++------- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a992507..5a9ea336 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] + - Changed CLI threads polling into blocking reads, to reduce CPU usage (@doegox) - Added support for timestamped comments in CLI via `rem`, `;`, `%` or `#` (@doegox) - Fixed watchdog trigger during `hw factory_reset` (@doegox) - Added PyInstaller support for CLI client (@augustozanellato) diff --git a/software/script/chameleon_com.py b/software/script/chameleon_com.py index eeee8d0b..726b61ea 100644 --- a/software/script/chameleon_com.py +++ b/software/script/chameleon_com.py @@ -5,6 +5,8 @@ import serial import chameleon_status +# each thread is waiting for its data for 100 ms before looping again +THREAD_BLOCKING_TIMEOUT = 0.1 class NotOpenException(Exception): """ @@ -82,7 +84,7 @@ def open(self, port): except Exception: # not all serial support dtr, e.g. virtual serial over BLE pass - self.serial_instance.timeout = 0 # do not block + self.serial_instance.timeout = THREAD_BLOCKING_TIMEOUT # clear variable self.send_data_queue.queue.clear() self.wait_response_map.clear() @@ -208,8 +210,6 @@ def thread_data_receive(self): data_buffer.clear() continue data_position += 1 - else: - time.sleep(0.001) def thread_data_transfer(self): """ @@ -218,10 +218,10 @@ def thread_data_transfer(self): """ while self.isOpen(): # get a task from queue(if exists) - if self.send_data_queue.empty(): - time.sleep(0.001) + try: + task = self.send_data_queue.get(block=True, timeout=THREAD_BLOCKING_TIMEOUT) + except queue.Empty: continue - task = self.send_data_queue.get() task_cmd = task['cmd'] task_timeout = task['timeout'] task_close = task['close'] @@ -262,7 +262,7 @@ def thread_check_timeout(self): else: # sync mode, set timeout flag self.wait_response_map[task_cmd]['is_timeout'] = True - time.sleep(0.001) + time.sleep(THREAD_BLOCKING_TIMEOUT) def make_data_frame_bytes(self, cmd: int, data: bytearray = None, status: int = 0) -> bytearray: """