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