Last active
November 19, 2024 05:53
-
-
Save NatLee/22cc6b86d1364a3ec398cefc5d2f640d to your computer and use it in GitHub Desktop.
Get USB Camera information with system command `udevadm` in Linux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import uuid | |
| import subprocess | |
| import gc | |
| from pathlib import Path | |
| from loguru import logger | |
| def cat_output(command:str): | |
| """ | |
| Use `python` to do system calls with `subproess`. | |
| Parameters | |
| ---------- | |
| command : str | |
| Command string. | |
| Returns | |
| ------- | |
| Str | |
| Return the result with command. | |
| """ | |
| result = '' | |
| try: | |
| result = subprocess.check_output(command, shell=True, close_fds=True).decode() | |
| except Exception as e: | |
| print(f'[cat_output] {e}') | |
| gc.collect() | |
| logger.error(f'[cat_output] {e}') | |
| return result | |
| def get_camera_info(camera:str): | |
| """ | |
| Get serial ID of camera. | |
| Parameters | |
| ---------- | |
| camera : str | |
| Path of device. | |
| Returns | |
| ------- | |
| Str | |
| Return camera ID. | |
| """ | |
| camera_uid = None | |
| params=['ID_SERIAL_SHORT', 'ID_USB_INTERFACES'] | |
| try : | |
| for i, param in enumerate(params): | |
| # system call for camera ID | |
| cmd = "udevadm info --query=all --name="+camera+" | grep "+param+" | sed 's/E: "+param+"=//' | sed -z 's/\\n//g'" | |
| camera_uid = cat_output(cmd) | |
| if camera_uid != '': | |
| break | |
| except Exception as e: | |
| logger.error(f'[get_camera_info] {e}') | |
| finally: | |
| if i == 1 and camera_uid != '': | |
| camera_uid = str(uuid.uuid5(uuid.NAMESPACE_DNS, camera_uid)) | |
| elif camera_uid == '': | |
| logger.warning(f'[get_camera_info] Camera ID not found {camera}') | |
| # no ID, use UUID | |
| camera_uid = str(uuid.uuid4()) | |
| return camera_uid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment