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