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