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