]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/generic_linux/sysfs_pwmout.py
Add timout loop after exporting the PWM pin.
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / generic_linux / sysfs_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
18 class PWMError(IOError):
19     """Base class for PWM errors."""
20
21     pass
22
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 scucessful PWM export on open (100ms)
33     PWM_STAT_DELAY = 0.1
34
35     # Number of retries to check for successful PWM export on open
36     PWM_STAT_RETRIES = 10
37     # Delay between check for scucessful PWM export on open (100ms)
38     PWM_STAT_DELAY = 0.1
39
40     # Number of retries to check for successful PWM export on open
41     PWM_STAT_RETRIES = 10
42     # Delay between check for scucessful PWM export on open (100ms)
43     PWM_STAT_DELAY = 0.1
44
45     # Sysfs paths
46     _sysfs_path = "/sys/class/pwm/"
47     _channel_path = "pwmchip{}"
48
49     # Channel paths
50     _export_path = "export"
51     _unexport_path = "unexport"
52     _pin_path = "pwm{}"
53
54     # Pin attribute paths
55     _pin_period_path = "period"
56     _pin_duty_cycle_path = "duty_cycle"
57     _pin_polarity_path = "polarity"
58     _pin_enable_path = "enable"
59
60     def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
61         """Instantiate a PWM object and open the sysfs PWM corresponding to the
62         specified channel and pin.
63
64         Args:
65             pin (Pin): CircuitPython Pin object to output to
66             duty_cycle (int) : The fraction of each pulse which is high. 16-bit
67             frequency (int) : target frequency in Hertz (32-bit)
68             variable_frequency (bool) : True if the frequency will change over time
69
70         Returns:
71             PWMOut: PWMOut object.
72
73         Raises:
74             PWMError: if an I/O or OS error occurs.
75             TypeError: if `channel` or `pin` types are invalid.
76             ValueError: if PWM channel does not exist.
77
78         """
79
80         self._pwmpin = None
81         self._channel = None
82         self._period = 0
83         self._open(pin, duty_cycle, frequency, variable_frequency)
84
85     def __del__(self):
86         self.deinit()
87
88     def __enter__(self):
89         return self
90
91     def __exit__(self, t, value, traceback):
92         self.deinit()
93
94     def _open(self, pin, duty=0, freq=500, variable_frequency=False):
95         self._channel = None
96         for pwmpair in pwmOuts:
97             if pwmpair[1] == pin:
98                 self._channel = pwmpair[0][0]
99                 self._pwmpin = pwmpair[0][1]
100
101         self._pin = pin
102         if self._channel is None:
103             raise RuntimeError("No PWM channel found for this Pin")
104
105         if variable_frequency:
106             print("Variable Frequency is not supported, continuing without it...")
107
108         channel_path = os.path.join(
109             self._sysfs_path, self._channel_path.format(self._channel)
110         )
111         if not os.path.isdir(channel_path):
112             raise ValueError(
113                 "PWM channel does not exist, check that the required modules are loaded."
114             )
115
116         try:
117             with open(
118                 os.path.join(channel_path, self._unexport_path), "w"
119             ) as f_unexport:
120                 f_unexport.write("%d\n" % self._pwmpin)
121         except IOError as e:
122             pass  # not unusual, it doesnt already exist
123         try:
124             with open(os.path.join(channel_path, self._export_path), "w") as f_export:
125                 f_export.write("%d\n" % self._pwmpin)
126         except IOError as e:
127             raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror) from IOError
128
129         # Loop until 'period' is writable, because application of udev rules
130         # after the above pin export is asynchronous.
131         # Without this loop, the following properties may not be writable yet.
132         for i in range(PWMOut.PWM_STAT_RETRIES):
133             try:
134                 with open(
135                     os.path.join(
136                         channel_path, self._pin_path.format(self._pwmpin), "period"
137                     ),
138                     "w",
139                 ):
140                     break
141             except IOError as e:
142                 if e.errno != EACCES or (
143                     e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1
144                 ):
145                     raise PWMError(e.errno, "Opening PWM period: " + e.strerror)
146             sleep(PWMOut.PWM_STAT_DELAY)
147
148         # self._set_enabled(False) # This line causes a write error when trying to enable
149
150         # Look up the period, for fast duty cycle updates
151         self._period = self._get_period()
152
153         # self.duty_cycle = 0  # This line causes a write error when trying to enable
154
155         # set frequency
156         self.frequency = freq
157         # set duty
158         self.duty_cycle = duty
159
160         self._set_enabled(True)
161
162     def deinit(self):
163         """Deinit the sysfs PWM."""
164         if self._channel is not None:
165             self.duty_cycle = 0
166             try:
167                 channel_path = os.path.join(
168                     self._sysfs_path, self._channel_path.format(self._channel)
169                 )
170                 with open(
171                     os.path.join(channel_path, self._unexport_path), "w"
172                 ) as f_unexport:
173                     f_unexport.write("%d\n" % self._pwmpin)
174             except IOError as e:
175                 raise PWMError(
176                     e.errno, "Unexporting PWM pin: " + e.strerror
177                 ) from IOError
178
179         self._channel = None
180         self._pwmpin = None
181
182     def _is_deinited(self):
183         if self._pwmpin is None:
184             raise ValueError(
185                 "Object has been deinitialize and can no longer "
186                 "be used. Create a new object."
187             )
188
189     def _write_pin_attr(self, attr, value):
190         # Make sure the pin is active
191         self._is_deinited()
192
193         path = os.path.join(
194             self._sysfs_path,
195             self._channel_path.format(self._channel),
196             self._pin_path.format(self._pwmpin),
197             attr,
198         )
199
200         with open(path, "w") as f_attr:
201             # print(value, path)
202             f_attr.write(value + "\n")
203
204     def _read_pin_attr(self, attr):
205         # Make sure the pin is active
206         self._is_deinited()
207
208         path = os.path.join(
209             self._sysfs_path,
210             self._channel_path.format(self._channel),
211             self._pin_path.format(self._pwmpin),
212             attr,
213         )
214
215         with open(path, "r") as f_attr:
216             return f_attr.read().strip()
217
218     # Mutable properties
219
220     def _get_period(self):
221         period_ns = self._read_pin_attr(self._pin_period_path)
222         try:
223             period_ns = int(period_ns)
224         except ValueError:
225             raise PWMError(
226                 None, 'Unknown period value: "%s"' % period_ns
227             ) from ValueError
228
229         # Convert period from nanoseconds to seconds
230         period = period_ns / 1e9
231
232         # Update our cached period
233         self._period = period
234
235         return period
236
237     def _set_period(self, period):
238         if not isinstance(period, (int, float)):
239             raise TypeError("Invalid period type, should be int or float.")
240
241         # Convert period from seconds to integer nanoseconds
242         period_ns = int(period * 1e9)
243
244         self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
245
246         # Update our cached period
247         self._period = float(period)
248
249     period = property(_get_period, _set_period)
250
251     """Get or set the PWM's output period in seconds.
252
253     Raises:
254         PWMError: if an I/O or OS error occurs.
255         TypeError: if value type is not int or float.
256
257     :type: int, float
258     """
259
260     def _get_duty_cycle(self):
261         duty_cycle_ns = self._read_pin_attr(self._pin_duty_cycle_path)
262         try:
263             duty_cycle_ns = int(duty_cycle_ns)
264         except ValueError:
265             raise PWMError(
266                 None, 'Unknown duty cycle value: "%s"' % duty_cycle_ns
267             ) from ValueError
268
269         # Convert duty cycle from nanoseconds to seconds
270         duty_cycle = duty_cycle_ns / 1e9
271
272         # Convert duty cycle to ratio from 0.0 to 1.0
273         duty_cycle = duty_cycle / self._period
274
275         # convert to 16-bit
276         duty_cycle = int(duty_cycle * 65535)
277         return duty_cycle
278
279     def _set_duty_cycle(self, duty_cycle):
280         if not isinstance(duty_cycle, (int, float)):
281             raise TypeError("Invalid duty cycle type, should be int or float.")
282
283         # convert from 16-bit
284         duty_cycle /= 65535.0
285         if not 0.0 <= duty_cycle <= 1.0:
286             raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
287
288         # Convert duty cycle from ratio to seconds
289         duty_cycle = duty_cycle * self._period
290
291         # Convert duty cycle from seconds to integer nanoseconds
292         duty_cycle_ns = int(duty_cycle * 1e9)
293
294         self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
295
296     duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
297     """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
298
299     Raises:
300         PWMError: if an I/O or OS error occurs.
301         TypeError: if value type is not int or float.
302         ValueError: if value is out of bounds of 0.0 to 1.0.
303
304     :type: int, float
305     """
306
307     def _get_frequency(self):
308         return 1.0 / self._get_period()
309
310     def _set_frequency(self, frequency):
311         if not isinstance(frequency, (int, float)):
312             raise TypeError("Invalid frequency type, should be int or float.")
313
314         self._set_period(1.0 / frequency)
315
316     frequency = property(_get_frequency, _set_frequency)
317     """Get or set the PWM's output frequency in Hertz.
318
319     Raises:
320         PWMError: if an I/O or OS error occurs.
321         TypeError: if value type is not int or float.
322
323     :type: int, float
324     """
325
326     def _get_enabled(self):
327         enabled = self._read_pin_attr(self._pin_enable_path)
328
329         if enabled == "1":
330             return True
331         if enabled == "0":
332             return False
333
334         raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
335
336     def _set_enabled(self, value):
337         """Get or set the PWM's output enabled state.
338
339         Raises:
340             PWMError: if an I/O or OS error occurs.
341             TypeError: if value type is not bool.
342
343         :type: bool
344         """
345         if not isinstance(value, bool):
346             raise TypeError("Invalid enabled type, should be string.")
347
348         self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
349
350     # String representation
351
352     def __str__(self):
353         return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
354             self._channel,
355             self._pin,
356             self.frequency,
357             self.duty_cycle * 100,
358         )