linusg / rpi-backlight

🔆 A Python module for controlling power and brightness of the official Raspberry Pi 7" touch display
https://rpi-backlight.readthedocs.io
MIT License
276 stars 32 forks source link

Automatic board detection for initiation #30

Closed p1r473 closed 3 years ago

p1r473 commented 3 years ago

Further fleshing out our discussion of automatic board detection/initiation so hopefully we don't need to manually initiate the board, in both init and CLI files.

I suppose if there's a reliable way to detect the board type, we could have automatic detection if no board type is explicitly provided - perhaps by checking the existence of each path in _BACKLIGHT_SYSFS_PATHS?

I was thinking of using /proc/device-tree/model

root@Harbormaster:~# cat /proc/device-tree/model
ASUS Tinker Board 2 (Linux Opensource)

What is the output on the Pi?

linusg commented 3 years ago

What is the output on the Pi?

$ cat /proc/device-tree/model
Raspberry Pi 3 Model B Rev 1.2
p1r473 commented 3 years ago

So it seems like this may be a good method for initiating the init and CLI files automatically I have taken a stab at the init file. Let me know what you think. You will probably have a much wiser way of implementing it.

__init.py__:

class Backlight:
    """Main class to access and control the display backlight power and brightness."""
    try:
      with open('/proc/device-tree/model','r') as f:
        for line in f:
          if line.startswith('ASUS Tinker Board 2'):
              boardDetection=BoardType.TINKER_BOARD_2
          elif line.startswith('ASUS Tinker Board'):
              boardDetection=BoardType.TINKER_BOARD
          elif line.startswith('Raspberry Pi'):
               boardDetection=BoardType.RASPBERRY_PI
          else:
               boardDetection=BoardType.RASPBERRY_PI
      except:
           raise RuntimeError("Invalid board type")

    def __init__(
        self,
        backlight_sysfs_path: Optional[Union[str, "PathLike[str]"]] = None,
        board_type: BoardType = boardDetection,
    ):

Not sure where we would put it for cli.py as there isnt much space in this section to work, its just all one parameter, and I seem to recall you disliking global variables

    parser.add_argument(
        "-B",
        "--board-type",
        default="raspberry-pi",
        choices=BOARD_TYPES.keys(),
        help="board type",
    )
linusg commented 3 years ago

Yeah, that looks about right - let's move that into a separate function, use modern path handling (pathlib.Path.read_text()), snake_case names. The try/except makes no sense, so skip it. No need to iterate lines either, startswith on the whole text is enough - it's only one line anyway.

By moving it into a function, it can also be re-used for the CLI.

p1r473 commented 3 years ago

The try,except was just in case the file doesn't exist But, it should exist on SBCs.

p1r473 commented 3 years ago

Fixed in https://github.com/linusg/rpi-backlight/pull/32