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