]> Repositories - Adafruit_Blinka-hackapet.git/blobdiff - src/adafruit_blinka/microcontroller/rockchip/PWMOut.py
Update PWMOut.py
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / rockchip / PWMOut.py
index f2509f48a2b00bb86447c66fa989cd0a4d64270b..09c4a8e2bb3ed62c7a607de28b51f8e8bdad1114 100644 (file)
@@ -1,3 +1,9 @@
+"""
+Much code from https://github.com/vsergeev/python-periphery/blob/master/periphery/pwm.py
+Copyright (c) 2015-2016 vsergeev / Ivan (Vanya) A. Sergeev
+License: MIT
+"""
+
 import os
 from time import sleep
 from errno import EACCES
@@ -8,12 +14,18 @@ except ImportError:
     raise RuntimeError("No PWM outputs defined for this board.") from ImportError
 
 
+# pylint: disable=unnecessary-pass, too-many-instance-attributes
+
+
 class PWMError(IOError):
     """Base class for PWM errors."""
 
     pass
 
 
+# pylint: enable=unnecessary-pass
+
+
 class PWMOut:
     """Pulse Width Modulation Output Class"""
 
@@ -23,20 +35,9 @@ class PWMOut:
     PWM_STAT_DELAY = 0.1
 
     # Sysfs paths
-    _sysfs_path = "/sys/class/pwm"
     _chip_path = "pwmchip{}"
     _channel_path = "pwm{}"
 
-    # Sysfs commands
-    _export = "export"
-    _unexport = "unexport"
-
-    # Pin commands
-    _pin_period = "period"
-    _pin_duty_cycle = "duty_cycle"
-    _pin_polarity = "polarity"
-    _pin_enable = "enable"
-
     def __init__(self, pwm, *, frequency=500, duty_cycle=0, variable_frequency=False):
         """Instantiate a PWM object and open the sysfs PWM corresponding to the
         specified chip and channel.
@@ -74,10 +75,15 @@ class PWMOut:
                 self._chip = pwmout[0][0]
                 self._channel = pwmout[0][1]
 
-        self._pwm = pwm
+        self._chip_path = os.path.join(
+            "/sys/class/pwm", self._chip_path.format(self._chip)
+        )
+        self._channel_path = os.path.join(
+            self._chip_path, self._channel_path.format(self._channel)
+        )
 
-        self._chip_path = os.path.join(self._sysfs_path, self._chip_path.format(self._chip))
-        self._channel_path = os.path.join(self._chip_path, self._channel_path.format(self._channel))
+        if variable_frequency:
+            print("Variable Frequency is not supported, continuing without it...")
 
         if not os.path.isdir(self._chip_path):
             raise LookupError("Opening PWM: PWM chip {} not found.".format(self._chip))
@@ -85,10 +91,12 @@ class PWMOut:
         if not os.path.isdir(self._channel_path):
             # Exporting the PWM.
             try:
-                with open(os.path.join(self._chip_path, self._export), "w") as f_export:
+                with open(os.path.join(self._chip_path, "export"), "w") as f_export:
                     f_export.write("{:d}\n".format(self._channel))
             except IOError as e:
-                raise PWMError(e.errno, "Exporting PWM channel: " + e.strerror)
+                raise PWMError(
+                    e.errno, "Exporting PWM channel: " + e.strerror
+                ) from IOError
 
             # Loop until PWM is exported
             exported = False
@@ -100,18 +108,29 @@ class PWMOut:
                 sleep(PWMOut.PWM_STAT_DELAY)
 
             if not exported:
-                raise TimeoutError("Exporting PWM: waiting for \"{:s}\" timed out.".format(self._channel_path))
+                raise TimeoutError(
+                    'Exporting PWM: waiting for "{:s}" timed out.'.format(
+                        self._channel_path
+                    )
+                )
 
             # Loop until 'period' is writable, This could take some time after
             # export as application of the udev rules after export is asynchronous.
             # Without this loop, the following properties may not be writable yet.
             for i in range(PWMOut.PWM_STAT_RETRIES):
                 try:
-                    with open(os.path.join(self._channel_path, "period"), "w",):
+                    with open(
+                        os.path.join(self._channel_path, "period"),
+                        "w",
+                    ):
                         break
                 except IOError as e:
-                    if e.errno != EACCES or (e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1):
-                        raise PWMError(e.errno, "Opening PWM period: " + e.strerror) from IOError
+                    if e.errno != EACCES or (
+                        e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1
+                    ):
+                        raise PWMError(
+                            e.errno, "Opening PWM period: " + e.strerror
+                        ) from IOError
 
                 sleep(PWMOut.PWM_STAT_DELAY)
 
@@ -126,31 +145,33 @@ class PWMOut:
         if self._channel is not None:
             # Unexporting the PWM channel
             try:
-                unexport_fd = os.open(os.path.join(self._chip_path, self._unexport), os.O_WRONLY)
+                unexport_fd = os.open(
+                    os.path.join(self._chip_path, "unexport"), os.O_WRONLY
+                )
                 os.write(unexport_fd, "{:d}\n".format(self._channel).encode())
                 os.close(unexport_fd)
             except OSError as e:
-                raise PWMError(e.errno, "Unexporting PWM: " + e.strerror)
+                raise PWMError(e.errno, "Unexporting PWM: " + e.strerror) from OSError
 
         self._chip = None
         self._channel = None
 
     def _write_channel_attr(self, attr, value):
-        with open(os.path.join(self._channel_path, attr), 'w') as f_attr:
+        with open(os.path.join(self._channel_path, attr), "w") as f_attr:
             f_attr.write(value + "\n")
 
     def _read_channel_attr(self, attr):
-        with open(os.path.join(self._channel_path, attr), 'r') as f_attr:
+        with open(os.path.join(self._channel_path, attr), "r") as f_attr:
             return f_attr.read().strip()
 
     # Methods
 
     def enable(self):
-        """Enable the PWM outout."""
+        """Enable the PWM output."""
         self.enabled = True
 
     def disable(self):
-        """Diable the PWM output."""
+        """Disable the PWM output."""
         self.enabled = False
 
     # Mutable properties
@@ -166,11 +187,11 @@ class PWMOut:
 
     period = property(_get_period, _set_period)
     """Get or set the PWM's output period in seconds.
-    
+
     Raises:
         PWMError: if an I/O or OS error occurs.
         TypeError: if value type is not int.
-        
+
     :type: int, float
     """
 
@@ -178,18 +199,18 @@ class PWMOut:
         return self.period_us / 1000
 
     def _set_period_ms(self, period_ms):
-        if not isinstance(period_ms, int):
-            raise TypeError("Invalid period type, should be int.")
+        if not isinstance(period_ms, (int, float)):
+            raise TypeError("Invalid period type, should be int or float.")
         self.period_us = int(period_ms * 1000)
 
     period_ms = property(_get_period_ms, _set_period_ms)
     """Get or set the PWM's output period in milliseconds.
-    
+
     Raises:
         PWMError: if an I/O or OS error occurs.
         TypeError: if value type is not int.
-        
-    :type: int
+
+    :type: int, float
     """
 
     def _get_period_us(self):
@@ -203,20 +224,22 @@ class PWMOut:
 
     period_us = property(_get_period_us, _set_period_us)
     """Get or set the PWM's output period in microseconds.
-    
+
     Raises:
         PWMError: if an I/O or OS error occurs.
         TypeError: if value type is not int.
-        
+
     :type: int
     """
 
     def _get_period_ns(self):
-        period_ns = self._read_channel_attr(self._pin_period)
+        period_ns = self._read_channel_attr("period")
         try:
             period_ns = int(period_ns)
         except ValueError:
-            raise PWMError(None, "Unknown period value: \"%s\"." % period_ns) from ValueError
+            raise PWMError(
+                None, 'Unknown period value: "%s".' % period_ns
+            ) from ValueError
 
         self._period_ns = period_ns
 
@@ -233,11 +256,11 @@ class PWMOut:
 
     period_ns = property(_get_period_ns, _set_period_ns)
     """Get or set the PWM's output period in nanoseconds.
-    
+
     Raises:
         PWMError: if an I/O or OS error occurs.
         TypeError: if value type is not int.
-        
+
     :type: int
     """
 
@@ -247,7 +270,9 @@ class PWMOut:
         try:
             duty_cycle_ns = int(duty_cycle_ns_str)
         except ValueError:
-            raise PWMError(None, "Unknown duty cycle value: \"{:s}\"".format(duty_cycle_ns_str))
+            raise PWMError(
+                None, 'Unknown duty cycle value: "{:s}"'.format(duty_cycle_ns_str)
+            ) from ValueError
 
         return duty_cycle_ns
 
@@ -259,11 +284,11 @@ class PWMOut:
 
     duty_cycle_ns = property(_get_duty_cycle_ns, _set_duty_cycle_ns)
     """Get or set the PWM's output duty cycle in nanoseconds.
-    
+
     Raises:
         PWMError: if an I/O or OS error occurs.
         TypeError: if value type is not int.
-        
+
     :type: int
     """
 
@@ -273,7 +298,8 @@ class PWMOut:
     def _set_duty_cycle(self, duty_cycle):
         if not isinstance(duty_cycle, (int, float)):
             raise TypeError("Invalid duty cycle type, should be int or float.")
-        elif not 0.0 <= duty_cycle <= 1.0:
+
+        if not 0.0 <= duty_cycle <= 1.0:
             raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
 
         # Convert duty cycle from ratio to nanoseconds
@@ -311,8 +337,9 @@ class PWMOut:
     def _set_polarity(self, polarity):
         if not isinstance(polarity, str):
             raise TypeError("Invalid polarity type, should be str.")
-        elif polarity.lower() not in ["normal", "inversed"]:
-            raise ValueError("Invalid polarity, can be: \"normal\" or \"inversed\".")
+
+        if polarity.lower() not in ["normal", "inversed"]:
+            raise ValueError('Invalid polarity, can be: "normal" or "inversed".')
 
         self._write_channel_attr("polarity", polarity.lower())
 
@@ -330,10 +357,10 @@ class PWMOut:
 
         if enabled == "1":
             return True
-        elif enabled == "0":
+        if enabled == "0":
             return False
 
-        raise PWMError(None, "Unknown enabled value: \"{:s}\"".format(enabled))
+        raise PWMError(None, 'Unknown enabled value: "{:s}"'.format(enabled))
 
     def _set_enabled(self, value):
         if not isinstance(value, bool):
@@ -352,5 +379,14 @@ class PWMOut:
     # String representation
 
     def __str__(self):
-        return "PWM {:d}, chip {:d} (period={:f} sec, duty_cycle={:f}%, polarity={:s}, enabled={:s})" \
-            .format(self._channel, self._chip, self.period, self.duty_cycle * 100, self.polarity, str(self.enabled))
\ No newline at end of file
+        return (
+            "PWM {:d}, chip {:d} (period={:f} sec, duty_cycle={:f}%,"
+            " polarity={:s}, enabled={:s})".format(
+                self._channel,
+                self._chip,
+                self.period,
+                self.duty_cycle * 100,
+                self.polarity,
+                str(self.enabled),
+            )
+        )