]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/rockchip/PWMOut.py
Add PWMOut
[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(self._sysfs_path, self._chip_path.format(self._chip))
80         self._channel_path = os.path.join(self._chip_path, self._channel_path.format(self._channel))
81
82         if not os.path.isdir(self._chip_path):
83             raise LookupError("Opening PWM: PWM chip {} not found.".format(self._chip))
84
85         if not os.path.isdir(self._channel_path):
86             # Exporting the PWM.
87             try:
88                 with open(os.path.join(self._chip_path, self._export), "w") as f_export:
89                     f_export.write("{:d}\n".format(self._channel))
90             except IOError as e:
91                 raise PWMError(e.errno, "Exporting PWM channel: " + e.strerror)
92
93             # Loop until PWM is exported
94             exported = False
95             for i in range(PWMOut.PWM_STAT_RETRIES):
96                 if os.path.isdir(self._channel_path):
97                     exported = True
98                     break
99
100                 sleep(PWMOut.PWM_STAT_DELAY)
101
102             if not exported:
103                 raise TimeoutError("Exporting PWM: waiting for \"{:s}\" timed out.".format(self._channel_path))
104
105             # Loop until 'period' is writable, This could take some time after
106             # export as application of the udev rules after export is asynchronous.
107             # Without this loop, the following properties may not be writable yet.
108             for i in range(PWMOut.PWM_STAT_RETRIES):
109                 try:
110                     with open(os.path.join(self._channel_path, "period"), "w",):
111                         break
112                 except IOError as e:
113                     if e.errno != EACCES or (e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1):
114                         raise PWMError(e.errno, "Opening PWM period: " + e.strerror) from IOError
115
116                 sleep(PWMOut.PWM_STAT_DELAY)
117
118             self.frequency = frequency
119             self.duty_cycle = duty_cycle
120
121             # Cache the period for fast duty cycle updates
122             self._period_ns = self._get_period_ns()
123
124     def close(self):
125         """Close the PWM."""
126         if self._channel is not None:
127             # Unexporting the PWM channel
128             try:
129                 unexport_fd = os.open(os.path.join(self._chip_path, self._unexport), os.O_WRONLY)
130                 os.write(unexport_fd, "{:d}\n".format(self._channel).encode())
131                 os.close(unexport_fd)
132             except OSError as e:
133                 raise PWMError(e.errno, "Unexporting PWM: " + e.strerror)
134
135         self._chip = None
136         self._channel = None
137
138     def _write_channel_attr(self, attr, value):
139         with open(os.path.join(self._channel_path, attr), 'w') as f_attr:
140             f_attr.write(value + "\n")
141
142     def _read_channel_attr(self, attr):
143         with open(os.path.join(self._channel_path, attr), 'r') as f_attr:
144             return f_attr.read().strip()
145
146     # Methods
147
148     def enable(self):
149         """Enable the PWM outout."""
150         self.enabled = True
151
152     def disable(self):
153         """Diable the PWM output."""
154         self.enabled = False
155
156     # Mutable properties
157
158     def _get_period(self):
159         return float(self.period_ms) / 1000
160
161     def _set_period(self, period):
162         if not isinstance(period, (int, float)):
163             raise TypeError("Invalid period type, should be int.")
164
165         self.period_ms = int(period * 1000)
166
167     period = property(_get_period, _set_period)
168     """Get or set the PWM's output period in seconds.
169     
170     Raises:
171         PWMError: if an I/O or OS error occurs.
172         TypeError: if value type is not int.
173         
174     :type: int, float
175     """
176
177     def _get_period_ms(self):
178         return self.period_us / 1000
179
180     def _set_period_ms(self, period_ms):
181         if not isinstance(period_ms, int):
182             raise TypeError("Invalid period type, should be int.")
183         self.period_us = int(period_ms * 1000)
184
185     period_ms = property(_get_period_ms, _set_period_ms)
186     """Get or set the PWM's output period in milliseconds.
187     
188     Raises:
189         PWMError: if an I/O or OS error occurs.
190         TypeError: if value type is not int.
191         
192     :type: int
193     """
194
195     def _get_period_us(self):
196         return self.period_ns / 1000
197
198     def _set_period_us(self, period_us):
199         if not isinstance(period_us, int):
200             raise TypeError("Invalid period type, should be int.")
201
202         self.period_ns = int(period_us * 1000)
203
204     period_us = property(_get_period_us, _set_period_us)
205     """Get or set the PWM's output period in microseconds.
206     
207     Raises:
208         PWMError: if an I/O or OS error occurs.
209         TypeError: if value type is not int.
210         
211     :type: int
212     """
213
214     def _get_period_ns(self):
215         period_ns = self._read_channel_attr(self._pin_period)
216         try:
217             period_ns = int(period_ns)
218         except ValueError:
219             raise PWMError(None, "Unknown period value: \"%s\"." % period_ns) from ValueError
220
221         self._period_ns = period_ns
222
223         return period_ns
224
225     def _set_period_ns(self, period_ns):
226         if not isinstance(period_ns, int):
227             raise TypeError("Invalid period type, should be int.")
228
229         self._write_channel_attr("period", str(period_ns))
230
231         # Update our cached period
232         self._period_ns = period_ns
233
234     period_ns = property(_get_period_ns, _set_period_ns)
235     """Get or set the PWM's output period in nanoseconds.
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_duty_cycle_ns(self):
245         duty_cycle_ns_str = self._read_channel_attr("duty_cycle")
246
247         try:
248             duty_cycle_ns = int(duty_cycle_ns_str)
249         except ValueError:
250             raise PWMError(None, "Unknown duty cycle value: \"{:s}\"".format(duty_cycle_ns_str))
251
252         return duty_cycle_ns
253
254     def _set_duty_cycle_ns(self, duty_cycle_ns):
255         if not isinstance(duty_cycle_ns, int):
256             raise TypeError("Invalid duty cycle type, should be int.")
257
258         self._write_channel_attr("duty_cycle", str(duty_cycle_ns))
259
260     duty_cycle_ns = property(_get_duty_cycle_ns, _set_duty_cycle_ns)
261     """Get or set the PWM's output duty cycle in nanoseconds.
262     
263     Raises:
264         PWMError: if an I/O or OS error occurs.
265         TypeError: if value type is not int.
266         
267     :type: int
268     """
269
270     def _get_duty_cycle(self):
271         return float(self.duty_cycle_ns) / self._period_ns
272
273     def _set_duty_cycle(self, duty_cycle):
274         if not isinstance(duty_cycle, (int, float)):
275             raise TypeError("Invalid duty cycle type, should be int or float.")
276         elif not 0.0 <= duty_cycle <= 1.0:
277             raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
278
279         # Convert duty cycle from ratio to nanoseconds
280         self.duty_cycle_ns = int(duty_cycle * self._period_ns)
281
282     duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
283     """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
284     Raises:
285         PWMError: if an I/O or OS error occurs.
286         TypeError: if value type is not int or float.
287         ValueError: if value is out of bounds of 0.0 to 1.0.
288     :type: int, float
289     """
290
291     def _get_frequency(self):
292         return 1.0 / self.period
293
294     def _set_frequency(self, frequency):
295         if not isinstance(frequency, (int, float)):
296             raise TypeError("Invalid frequency type, should be int or float.")
297
298         self.period = 1.0 / frequency
299
300     frequency = property(_get_frequency, _set_frequency)
301     """Get or set the PWM's output frequency in Hertz.
302     Raises:
303         PWMError: if an I/O or OS error occurs.
304         TypeError: if value type is not int or float.
305     :type: int, float
306     """
307
308     def _get_polarity(self):
309         return self._read_channel_attr("polarity")
310
311     def _set_polarity(self, polarity):
312         if not isinstance(polarity, str):
313             raise TypeError("Invalid polarity type, should be str.")
314         elif polarity.lower() not in ["normal", "inversed"]:
315             raise ValueError("Invalid polarity, can be: \"normal\" or \"inversed\".")
316
317         self._write_channel_attr("polarity", polarity.lower())
318
319     polarity = property(_get_polarity, _set_polarity)
320     """Get or set the PWM's output polarity. Can be "normal" or "inversed".
321     Raises:
322         PWMError: if an I/O or OS error occurs.
323         TypeError: if value type is not str.
324         ValueError: if value is invalid.
325     :type: str
326     """
327
328     def _get_enabled(self):
329         enabled = self._read_channel_attr("enable")
330
331         if enabled == "1":
332             return True
333         elif enabled == "0":
334             return False
335
336         raise PWMError(None, "Unknown enabled value: \"{:s}\"".format(enabled))
337
338     def _set_enabled(self, value):
339         if not isinstance(value, bool):
340             raise TypeError("Invalid enabled type, should be bool.")
341
342         self._write_channel_attr("enable", "1" if value else "0")
343
344     enabled = property(_get_enabled, _set_enabled)
345     """Get or set the PWM's output enabled state.
346     Raises:
347         PWMError: if an I/O or OS error occurs.
348         TypeError: if value type is not bool.
349     :type: bool
350     """
351
352     # String representation
353
354     def __str__(self):
355         return "PWM {:d}, chip {:d} (period={:f} sec, duty_cycle={:f}%, polarity={:s}, enabled={:s})" \
356             .format(self._channel, self._chip, self.period, self.duty_cycle * 100, self.polarity, str(self.enabled))