В моем проекте работает USB-монитор, но я вижу, что он мешает другим функциям, поэтому я хочу запускать/останавливать его при необходимости. В моем коде функция запуска в порядке, а функция остановки - нет, я не могу ее остановить.
Вот код:
#lots of import stuff#
# USB Monitoring Process (global variables to manage lifecycle,
# there are many due to the experiments I made trying to solve the issue)
usb_process = None
running = False
usb_monitor_thread = None
usb_monitor_started = False
def device_event_monitor(action, device):
if device.subsystem == 'usb':
if action == 'add' and device.device_type == 'usb_device':
# my code does stuff and get some info from the connected device
# especially gets some values to generate an hash
# to insert in a sql database
device_hash = hash_object.hexdigest()
if device_hash in hash_list:
cursor.execute(
"UPDATE devices SET connection_time = ? WHERE hash = ?",
(start_time, device_hash),
)
else:
# This is the part I can't get working: I want to stop monitor and
# start a device registration process through a webpage, but
# I see no message, the monitor does not stop, the page is not rendered
stop_usb_monitor()
print(f"STOP MONITOR!!")
with app.app_context():
return render_template("new_device.html")
def monitor_usb():
global running
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
monitor.filter_by('usb')
monitor.enable_receiving()
observer = pyudev.MonitorObserver(monitor, device_event_monitor)
observer.start()
try:
while running:
time.sleep(0.1)
except KeyboardInterrupt:
print("\nMonitor manually stopped.")
finally:
observer.stop()
print("Monitor USB stopped.")
def start_usb_monitor():
global running, usb_monitor_thread
if running:
print("Already running!")
return
running = True
usb_monitor_thread = threading.Thread(target=monitor_usb, daemon=True)
usb_monitor_thread.start()
print("\nMonitor started!")
def stop_usb_monitor():
global running, usb_monitor_thread
if not running:
print("Monitor not running!")
return
running = False
if usb_monitor_thread:
usb_monitor_thread.join() # Aspetta la terminazione del thread
print("Monitor USB stopped!")
@app.route("/")
def index():
return render_template("index.html")
@app.route('/start', methods=['POST'])
def start():
start_usb_monitor()
return render_template("table.html")
@app.route("/new_device", methods=["POST"])
def new_device():
device_name = request.form.get("owner_name")
if __name__ == "__main__":
# Start Flask app
app.run(debug=True)`
Извините, если мой код испорчен, я новичок и перепробовал множество переменных для запуска/остановки монитора. Я обнаружил одну вещь: JavaScript на моих html-страницах во многом мешал, поэтому я сохраняю страницы в простом html и получаю лучший результат (в основном для контроля запуска процесса мониторинга, сначала я запускал его автоматически).
В моем проекте работает USB-монитор, но я вижу, что он мешает другим функциям, поэтому я хочу запускать/останавливать его при необходимости. В моем коде функция запуска в порядке, а функция остановки - нет, я не могу ее остановить. Вот код: [code]#lots of import stuff#
# USB Monitoring Process (global variables to manage lifecycle, # there are many due to the experiments I made trying to solve the issue) usb_process = None running = False usb_monitor_thread = None usb_monitor_started = False
def device_event_monitor(action, device): if device.subsystem == 'usb': if action == 'add' and device.device_type == 'usb_device': # my code does stuff and get some info from the connected device # especially gets some values to generate an hash # to insert in a sql database device_hash = hash_object.hexdigest() if device_hash in hash_list: cursor.execute( "UPDATE devices SET connection_time = ? WHERE hash = ?", (start_time, device_hash), ) else: # This is the part I can't get working: I want to stop monitor and # start a device registration process through a webpage, but # I see no message, the monitor does not stop, the page is not rendered stop_usb_monitor() print(f"STOP MONITOR!!") with app.app_context(): return render_template("new_device.html")
def start_usb_monitor(): global running, usb_monitor_thread if running: print("Already running!") return running = True usb_monitor_thread = threading.Thread(target=monitor_usb, daemon=True) usb_monitor_thread.start() print("\nMonitor started!")
def stop_usb_monitor(): global running, usb_monitor_thread if not running: print("Monitor not running!") return running = False if usb_monitor_thread: usb_monitor_thread.join() # Aspetta la terminazione del thread print("Monitor USB stopped!")
if __name__ == "__main__": # Start Flask app app.run(debug=True)` [/code] Извините, если мой код испорчен, я новичок и перепробовал множество переменных для запуска/остановки монитора. Я обнаружил одну вещь: JavaScript на моих html-страницах во многом мешал, поэтому я сохраняю страницы в простом html и получаю лучший результат (в основном для контроля запуска процесса мониторинга, сначала я запускал его автоматически).