]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/rockchip/PWMOut.py
Merge branch 'lgpio-native' of https://github.com/frank-pet/Adafruit_Blinka into...
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / rockchip / PWMOut.py
1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
2 #
3 # SPDX-License-Identifier: MIT
4 """
5 Much code from https://github.com/vsergeev/python-periphery/blob/master/periphery/pwm.py
6 Copyright (c) 2015-2016 vsergeev / Ivan (Vanya) A. Sergeev
7 License: MIT
8 """
9
10 import os
11 from time import sleep
12 from errno import EACCES
13
14 try:
15     from microcontroller.pin import pwmOuts
16 except ImportError:
17     raise RuntimeError("No PWM outputs defined for this board.") from ImportError
18
19
20 # pylint: disable=unnecessary-pass, too-many-instance-attributes
21
22
23 class PWMError(IOError):
24     """Base class for PWM errors."""
25
26     pass
27
28
29 # pylint: enable=unnecessary-pass
30
31
32 class PWMOut:
33     """Pulse Width Modulation Output Class"""
34
35     # Number of retries to check for successful PWM export on open
36     PWM_STAT_RETRIES = 10
37     # Delay between check for successful PWM export on open (100ms)
38     PWM_STAT_DELAY = 0.1
39
40     # Sysfs paths
41     _chip_path = "pwmchip{}"
42     _channel_path = "pwm{}"
43
44     def __init__(self, pwm, *, frequency=500, duty_cycle=0, variable_frequency=False):
45         """Instantiate a PWM object and open the sysfs PWM corresponding to the
46         specified chip and channel.
47         Args:
48             pwm (str): PWM pin.
49             frequency (int, float): target frequency in Hertz (32-bit).
50             duty_cycle (int, float): The fraction of each pulse which is high (16-bit).
51             variable_frequency (bool): True if the frequency will change over time.
52         Returns:
53             PWM: PWM object.
54         Raises:
55             PWMError: if an I/O or OS error occurs.
56             TypeError: if `chip` or `channel` types are invalid.
57             LookupError: if PWM chip does not exist.
58             TimeoutError: if waiting for PWM export times out.
59         """
60
61         self._chip = None
62         self._channel = None
63         self._period_ns = 0
64         self._open(pwm, frequency, duty_cycle, variable_frequency)
65
66     def __del__(self):
67         self.close()
68
69     def __enter__(self):
70         return self
71
72     def __exit__(self, exc_type, exc_val, exc_tb):
73         self.close()
74
75     def _open(self, pwm, frequency, duty_cycle, variable_frequency):
76         for pwmout in pwmOuts:
77             if pwmout[1] == pwm:
78                 self._chip = pwmout[0][0]
79                 self._channel = pwmout[0][1]
80
81         self._chip_path = os.path.join(
82             "/sys/class/pwm", self._chip_path.format(self._chip)
83         )
84         self._channel_path = os.path.join(
85             self._chip_path, self._channel_path.format(self._channel)
86         )
87
88         if variable_frequency:
89             print("Variable Frequency is not supported, continuing without it...")
90
91         if not os.path.isdir(self._chip_path):
92             raise LookupError("Opening PWM: PWM chip {} not found.".format(self._chip))
93
94         if not os.path.isdir(self._channel_path):
95             # Exporting the PWM.
96             try:
97                 with open(
98                     os.path.join(self._chip_path, "export"), "w", encoding="utf-8"
99                 ) as f_export:
100                     f_export.write("{:d}\n".format(self._channel))
101             except IOError as e:
102                 raise PWMError(
103                     e.errno, "Exporting PWM channel: " + e.strerror
104                 ) from IOError
105
106             # Loop until PWM is exported
107             exported = False
108             for i in range(PWMOut.PWM_STAT_RETRIES):
109                 if os.path.isdir(self._channel_path):
110                     exported = True
111                     break
112
113                 sleep(PWMOut.PWM_STAT_DELAY)
114
115             if not exported:
116                 raise TimeoutError(
117                     'Exporting PWM: waiting for "{:s}" timed out.'.format(
118                         self._channel_path
119                     )
120                 )
121
122             # Loop until 'period' is writable, This could take some time after
123             # export as application of the udev rules after export is asynchronous.
124             # Without this loop, the following properties may not be writable yet.
125             for i in range(PWMOut.PWM_STAT_RETRIES):
126                 try:
127                     with open(
128                         os.path.join(self._channel_path, "period"),
129                         "w",
130                         encoding="utf-8",
131                     ):
132                         break
133                 except IOError as e:
134                     if e.errno != EACCES or (
135                         e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1
136                     ):
137                         raise PWMError(
138                             e.errno, "Opening PWM period: " + e.strerror
139                         ) from IOError
140
141                 sleep(PWMOut.PWM_STAT_DELAY)
142
143             self.frequency = frequency
144             self.duty_cycle = duty_cycle
145             self.polarity = "normal"
146             self.enable()
147
148             # Cache the period for fast duty cycle updates
149             self._period_ns = self._get_period_ns()
150
151     def close(self):
152         """Close the PWM."""
153         if self._channel is not None:
154             # Unexporting the PWM channel
155             try:
156                 unexport_fd = os.open(
157                     os.path.join(self._chip_path, "unexport"), os.O_WRONLY
158                 )
159                 os.write(unexport_fd, "{:d}\n".format(self._channel).encode())
160                 os.close(unexport_fd)
161             except OSError as e:
162                 raise PWMError(e.errno, "Unexporting PWM: " + e.strerror) from OSError
163
164         self._chip = None
165         self._channel = None
166
167     def _write_channel_attr(self, attr, value):
168         with open(
169             os.path.join(self._channel_path, attr), "w", encoding="utf-8"
170         ) as f_attr:
171             f_attr.write(value + "\n")
172
173     def _read_channel_attr(self, attr):
174         with open(
175             os.path.join(self._channel_path, attr), "r", encoding="utf-8"
176         ) as f_attr:
177             return f_attr.read().strip()
178
179     # Methods
180
181     def enable(self):
182         """Enable the PWM output."""
183         self.enabled = True
184
185     def disable(self):
186         """Disable the PWM output."""
187         self.enabled = False
188
189     # Mutable properties
190
191     def _get_period(self):
192         return float(self.period_ms) / 1000
193
194     def _set_period(self, period):
195         if not isinstance(period, (int, float)):
196             raise TypeError("Invalid period type, should be int.")
197
198         self.period_ms = int(period * 1000)
199
200     period = property(_get_period, _set_period)
201     """Get or set the PWM's output period in seconds.
202
203     Raises:
204         PWMError: if an I/O or OS error occurs.
205         TypeError: if value type is not int.
206
207     :type: int, float
208     """
209
210     def _get_period_ms(self):
211         return self.period_us / 1000
212
213     def _set_period_ms(self, period_ms):
214         if not isinstance(period_ms, (int, float)):
215             raise TypeError("Invalid period type, should be int or float.")
216         self.period_us = int(period_ms * 1000)
217
218     period_ms = property(_get_period_ms, _set_period_ms)
219     """Get or set the PWM's output period in milliseconds.
220
221     Raises:
222         PWMError: if an I/O or OS error occurs.
223         TypeError: if value type is not int.
224
225     :type: int, float
226     """
227
228     def _get_period_us(self):
229         return self.period_ns / 1000
230
231     def _set_period_us(self, period_us):
232         if not isinstance(period_us, int):
233             raise TypeError("Invalid period type, should be int.")
234
235         self.period_ns = int(period_us * 1000)
236
237     period_us = property(_get_period_us, _set_period_us)
238     """Get or set the PWM's output period in microseconds.
239
240     Raises:
241         PWMError: if an I/O or OS error occurs.
242         TypeError: if value type is not int.
243
244     :type: int
245     """
246
247     def _get_period_ns(self):
248         period_ns = self._read_channel_attr("period")
249         try:
250             period_ns = int(period_ns)
251         except ValueError:
252             raise PWMError(
253                 None, 'Unknown period value: "%s".' % period_ns
254             ) from ValueError
255
256         self._period_ns = period_ns
257
258         return period_ns
259
260     def _set_period_ns(self, period_ns):
261         if not isinstance(period_ns, int):
262             raise TypeError("Invalid period type, should be int.")
263
264         self._write_channel_attr("period", str(period_ns))
265
266         # Update our cached period
267         self._period_ns = period_ns
268
269     period_ns = property(_get_period_ns, _set_period_ns)
270     """Get or set the PWM's output period in nanoseconds.
271
272     Raises:
273         PWMError: if an I/O or OS error occurs.
274         TypeError: if value type is not int.
275
276     :type: int
277     """
278
279     def _get_duty_cycle_ns(self):
280         duty_cycle_ns_str = self._read_channel_attr("duty_cycle")
281
282         try:
283             duty_cycle_ns = int(duty_cycle_ns_str)
284         except ValueError:
285             raise PWMError(
286                 None, 'Unknown duty cycle value: "{:s}"'.format(duty_cycle_ns_str)
287             ) from ValueError
288
289         return duty_cycle_ns
290
291     def _set_duty_cycle_ns(self, duty_cycle_ns):
292         if not isinstance(duty_cycle_ns, int):
293             raise TypeError("Invalid duty cycle type, should be int.")
294
295         self._write_channel_attr("duty_cycle", str(duty_cycle_ns))
296
297     duty_cycle_ns = property(_get_duty_cycle_ns, _set_duty_cycle_ns)
298     """Get or set the PWM's output duty cycle in nanoseconds.
299
300     Raises:
301         PWMError: if an I/O or OS error occurs.
302         TypeError: if value type is not int.
303
304     :type: int
305     """
306
307     def _get_duty_cycle(self):
308         return float(self.duty_cycle_ns) / self._period_ns
309
310     def _set_duty_cycle(self, duty_cycle):
311         if not isinstance(duty_cycle, (int, float)):
312             raise TypeError("Invalid duty cycle type, should be int or float.")
313
314         if not 0.0 <= duty_cycle <= 1.0:
315             raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
316
317         # Convert duty cycle from ratio to nanoseconds
318         self.duty_cycle_ns = int(duty_cycle * self._period_ns)
319
320     duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
321     """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
322     Raises:
323         PWMError: if an I/O or OS error occurs.
324         TypeError: if value type is not int or float.
325         ValueError: if value is out of bounds of 0.0 to 1.0.
326     :type: int, float
327     """
328
329     def _get_frequency(self):
330         return 1.0 / self.period
331
332     def _set_frequency(self, frequency):
333         if not isinstance(frequency, (int, float)):
334             raise TypeError("Invalid frequency type, should be int or float.")
335
336         self.period = 1.0 / frequency
337
338     frequency = property(_get_frequency, _set_frequency)
339     """Get or set the PWM's output frequency in Hertz.
340     Raises:
341         PWMError: if an I/O or OS error occurs.
342         TypeError: if value type is not int or float.
343     :type: int, float
344     """
345
346     def _get_polarity(self):
347         return self._read_channel_attr("polarity")
348
349     def _set_polarity(self, polarity):
350         if not isinstance(polarity, str):
351             raise TypeError("Invalid polarity type, should be str.")
352
353         if polarity.lower() not in ["normal", "inversed"]:
354             raise ValueError('Invalid polarity, can be: "normal" or "inversed".')
355
356         self._write_channel_attr("polarity", polarity.lower())
357
358     polarity = property(_get_polarity, _set_polarity)
359     """Get or set the PWM's output polarity. Can be "normal" or "inversed".
360     Raises:
361         PWMError: if an I/O or OS error occurs.
362         TypeError: if value type is not str.
363         ValueError: if value is invalid.
364     :type: str
365     """
366
367     def _get_enabled(self):
368         enabled = self._read_channel_attr("enable")
369
370         if enabled == "1":
371             return True
372         if enabled == "0":
373             return False
374
375         raise PWMError(None, 'Unknown enabled value: "{:s}"'.format(enabled))
376
377     def _set_enabled(self, value):
378         if not isinstance(value, bool):
379             raise TypeError("Invalid enabled type, should be bool.")
380
381         self._write_channel_attr("enable", "1" if value else "0")
382
383     enabled = property(_get_enabled, _set_enabled)
384     """Get or set the PWM's output enabled state.
385     Raises:
386         PWMError: if an I/O or OS error occurs.
387         TypeError: if value type is not bool.
388     :type: bool
389     """
390
391     # String representation
392
393     def __str__(self):
394         return (
395             "PWM {:d}, chip {:d} (period={:f} sec, duty_cycle={:f}%,"
396             " polarity={:s}, enabled={:s})".format(
397                 self._channel,
398                 self._chip,
399                 self.period,
400                 self.duty_cycle * 100,
401                 self.polarity,
402                 str(self.enabled),
403             )
404         )