подключении до четырех USB-устройств с одинаковыми идентификаторами производителя и продукта USB.Для этого я создал правило udev в /etc/udev/rules.d/myrule.rules следующим образом:
Код: Выделить всё
ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="1234", ATTR{idProduct}=="5678", ENV{SYSTEMD_WANTS}="usb-trigger.service"
Кроме того, я настроил службу systemd в /etc/systemd/system/usb-trigger .service со следующей конфигурацией:
Код: Выделить всё
[Unit]
Description=USB Trigger Service
[Service]
Type=oneshot
ExecStart=/path/to/my/python/script/uart.py
[Install]
WantedBy=multi-user.target
Основная цель моего сценария Python – создать CSV-файл при подключении USB-устройства, сохранить данные и закрыть файл при устройство отключено. Мне нужен этот сценарий для обработки до четырех устройств.
Вот сценарий Python, который я использую:
Код: Выделить всё
python
import serial
import serial.tools.list_ports
import time
import csv
import datetime
import sys
def get_current_time():
current_time = time.time()
milliseconds = int((current_time - int(current_time)) * 1000)
formatted_time = time.strftime("%H:%M:%S", time.localtime(current_time))
formatted_time += f".{milliseconds:03d}" # Adding milliseconds
return formatted_time
def write_to_csv(writer, data):
try:
writer.writerow(data)
except Exception as e:
print(f"Error writing to CSV: {e}")
def find_com_port():
try:
com_ports = serial.tools.list_ports.comports()
for port in com_ports:
if port.device.startswith('/dev/ttyUSB') or port.device.startswith('/dev/ttyACM'):
return port.device
except Exception as e:
print(f"Error finding COM port: {e}")
def main():
try:
while True:
com_port = find_com_port()
if com_port is not None:
print(f"COM port found: {com_port}")
break # Exit the loop once a COM port is found
else:
print("No COM port found. Retrying...")
time.sleep(1)
if com_port is None:
print("No COM port found.")
return
filename = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ".csv"
bottle_id = None
bottle_id_collected = False # Flag to track if bottle ID has been collected
with serial.Serial(port=com_port, baudrate=460800, timeout=2) as ser, open(filename, 'w', newline='') as file:
print(f"Connected to {com_port} successfully.")
writer = csv.writer(file)
while True:
received_bytes = ser.readline().decode('ascii', errors='replace').strip()
if received_bytes:
if not bottle_id_collected and 'Bottle ID' in received_bytes:
bottle_id = received_bytes.split('Bottle ID')[1].strip()
writer.writerow(['Bottle ID', bottle_id])
writer.writerow(['Input 1', 'Input 2', 'Input 3', 'time stamp'])
bottle_id_collected = True
else:
parts = received_bytes.split(', ')
try:
numbers = [float(part) for part in parts]
data_row = numbers + [get_current_time()]
writer.writerow(data_row)
print(f"Writing to CSV: {data_row}")
file.flush() # Force flushing
except ValueError as e:
pass
time.sleep(0.01)
except serial.SerialException as e:
print(f"Error opening serial port {com_port}: {e}")
except KeyboardInterrupt:
print("Program terminated by user.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
try:
if 'ser' in locals() and ser.is_open:
ser.close()
except Exception as e:
print(f"Error closing serial port: {e}")
try:
if 'file' in locals() and not file.closed:
file.close()
except Exception as e:
print(f"Error closing CSV file: {e}")
sys.exit()
if __name__ == "__main__":
main()
Я настроил правило udev и службу systemd для запуска сценария Python при подключении нескольких USB-устройств с одинаковыми идентификаторами. Я ожидал, что сценарий надежно сгенерирует CSV-файл для каждого устройства, одновременно обрабатывая до четырех устройств. Однако сценарий иногда не запускался, особенно при подключении нескольких устройств, что приводило к нестабильному поведению.
Подробнее здесь: https://stackoverflow.com/questions/783 ... t-problems