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