]> Repositories - Adafruit_Blinka-hackapet.git/blobdiff - src/adafruit_blinka/microcontroller/amlogic/meson_g12_common/pin.py
Merge pull request #714 from makermelissa/missing-bbio
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / amlogic / meson_g12_common / pin.py
index 165bca71db19a9a3b4c7340212f4aaf5f7ca5b9d..1f9fa3c941d76b3041cdca35260eff73e2f52ee4 100644 (file)
@@ -1,3 +1,6 @@
+# SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
+#
+# SPDX-License-Identifier: MIT
 """
 G12A, G12B, and SM1 Common Definitions
 Ref:
@@ -8,24 +11,46 @@ Linux kernel 5.4.y (mainline)
     linux/arch/arm64/boot/dts/amlogic/meson-g12-common.dtsi
 """
 
+from typing import Optional
+import os
 import re
+
+try:
+    import gpiod
+except ImportError:
+    raise ImportError(
+        "libgpiod Python bindings not found, please install and try again!"
+    ) from ImportError
 from adafruit_blinka.microcontroller.generic_linux.libgpiod_pin import Pin
-import gpiod
 
-chip0 = gpiod.Chip("0")
-chip1 = gpiod.Chip("1")
+if hasattr(gpiod, "Chip"):
+    chip0 = gpiod.Chip("0")
+    chip1 = gpiod.Chip("1")
+else:
+    chip0 = gpiod.chip("0")
+    chip1 = gpiod.chip("1")
+
+if callable(chip0.num_lines):
+    chip0lines = chip0.num_lines()
+else:
+    chip0lines = chip0.num_lines
+
+if callable(chip1.num_lines):
+    chip1lines = chip1.num_lines()
+else:
+    chip1lines = chip1.num_lines
 
-if chip0.num_lines() < 20:
+if chip0lines < 20:
     aobus = 0
     periphs = 1
-    periphs_offset = chip1.num_lines() - 85
+    periphs_offset = chip1lines - 85
 else:
     aobus = 1
     periphs = 0
-    periphs_offset = chip0.num_lines() - 85
+    periphs_offset = chip0lines - 85
 
-chip0.close()
-chip1.close()
+del chip0
+del chip1
 
 GPIOAO_0 = GPIO496 = Pin((aobus, 0))
 GPIOAO_1 = GPIO497 = Pin((aobus, 1))
@@ -107,18 +132,18 @@ UART1_RX = GPIOX_13
 uartPorts = ((1, UART1_TX, UART1_RX),)
 
 
-def get_dts_alias(device: str) -> str:
+def get_dts_alias(device: str) -> Optional[str]:
     """Get the Device Tree Alias"""
     uevent_path = "/sys/bus/platform/devices/" + device + "/uevent"
-    with open(uevent_path, "r") as fd:
-        pattern = r"^OF_ALIAS_0=(.*)$"
-        uevent = fd.read().split("\n")
-        for line in uevent:
-            match = re.search(pattern, line)
-            if match:
-                return match.group(1).upper()
-
-        return None
+    if os.path.exists(uevent_path):
+        with open(uevent_path, "r", encoding="utf-8") as fd:
+            pattern = r"^OF_ALIAS_0=(.*)$"
+            uevent = fd.read().split("\n")
+            for line in uevent:
+                match = re.search(pattern, line)
+                if match:
+                    return match.group(1).upper()
+    return None
 
 
 # ordered as i2cId, sclId, sdaId