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