├── CHIP_IO ├── __init__.py ├── Utilities.py ├── LRADC.py └── OverlayManager.py ├── debian ├── compat ├── source │ └── format ├── files ├── rules ├── control └── changelog ├── .gitignore ├── docs ├── _config.yml ├── utilities.md ├── overlaymanager.md ├── servo.md ├── softpwm.md ├── pwm.md ├── lradc.md ├── index.md └── gpio.md ├── setup.cfg ├── MANIFEST.in ├── unexport_all.sh ├── tox.ini ├── test ├── test_utilities.py ├── test_lradc.py ├── test_gpio_input.py ├── integrations │ ├── spwmtest2.py │ ├── omtest.py │ ├── lradctest.py │ ├── spwmtest.py │ ├── servotest.py │ ├── pwmtest.py │ └── gptest.py ├── test_gpio_output.py ├── test_gpio_setup.py ├── test_softpwm_setup.py └── test_pwm_setup.py ├── source ├── constants.h ├── c_softpwm.h ├── c_softservo.h ├── c_pwm.h ├── event_gpio.h ├── constants.c ├── common.h ├── c_softpwm.c ├── c_softservo.c ├── py_servo.c ├── py_softpwm.c └── py_pwm.c ├── fix_py_compile.py ├── LICENSE ├── Makefile ├── setup.py ├── CHANGELOG.rst └── distribute_setup.py /CHIP_IO/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /debian/compat: -------------------------------------------------------------------------------- 1 | 9 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .ropeproject/ 2 | -------------------------------------------------------------------------------- /debian/source/format: -------------------------------------------------------------------------------- 1 | 3.0 (quilt) 2 | -------------------------------------------------------------------------------- /docs/_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-minimal -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal = 1 3 | 4 | [metadata] 5 | license_file = LICENSE 6 | 7 | -------------------------------------------------------------------------------- /debian/files: -------------------------------------------------------------------------------- 1 | python-chip-io_0.7.1-1_armhf.deb python optional 2 | python3-chip-io_0.7.1-1_armhf.deb python optional 3 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include distribute_setup.py 2 | include README.rst 3 | include CHANGELOG.rst 4 | recursive-include source *.h 5 | -------------------------------------------------------------------------------- /unexport_all.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | for F in /sys/class/gpio/gpio[0-9]*; do : 4 | GPIO=`echo $F | sed 's/^[^0-9]*//'` 5 | echo $F $GPIO 6 | echo $GPIO >/sys/class/gpio/unexport 7 | done 8 | -------------------------------------------------------------------------------- /debian/rules: -------------------------------------------------------------------------------- 1 | #!/usr/bin/make -f 2 | 3 | # This file was automatically generated by stdeb 0.8.2 at 4 | # Sat, 18 Feb 2017 23:58:48 +0000 5 | export PYBUILD_NAME=chip-io 6 | 7 | %: 8 | dh $@ --with python2,python3 --buildsystem=pybuild 9 | 10 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | # Tox (http://tox.testrun.org/) is a tool for running tests 2 | # in multiple virtualenvs. This configuration file will run the 3 | # test suite on all supported python versions. To use it, "pip install tox" 4 | # and then run "tox" from this directory. 5 | 6 | [tox] 7 | envlist = py27, py34 8 | 9 | [testenv] 10 | commands = 11 | deps = 12 | -------------------------------------------------------------------------------- /test/test_utilities.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | import CHIP_IO.Utilities as UT 4 | 5 | class TestUtilities: 6 | def test_invalid_set_1v8_with_string(self): 7 | assert not UT.set_1v8_pin_voltage("yaystring") 8 | 9 | def test_invalid_set_1v8_with_outofbounds_value(self): 10 | assert not UT.set_1v8_pin_voltage(0.5) 11 | assert not UT.set_1v8_pin_voltage(4.5) 12 | -------------------------------------------------------------------------------- /source/constants.h: -------------------------------------------------------------------------------- 1 | PyObject *high; 2 | PyObject *low; 3 | PyObject *input; 4 | PyObject *output; 5 | PyObject *alt0; 6 | PyObject *pud_off; 7 | PyObject *pud_up; 8 | PyObject *pud_down; 9 | PyObject *rising_edge; 10 | PyObject *falling_edge; 11 | PyObject *both_edge; 12 | PyObject *version; 13 | PyObject *unknown; 14 | PyObject *board; 15 | PyObject *bcm; 16 | 17 | void define_constants(PyObject *module); 18 | -------------------------------------------------------------------------------- /test/test_lradc.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | import CHIP_IO.LRADC as LRADC 4 | 5 | class TestLRADC: 6 | def test_scale_factor(self): 7 | assert LRADC.get_scale_factor() == 31.25 8 | 9 | def test_sample_rate_values(self): 10 | assert LRADC.get_allowable_sample_rates() == (32.25, 62.5, 125, 250) 11 | 12 | def test_set_sample_rate(self): 13 | LRADC.set_sample_rate(32.25) 14 | assert LRADC.get_sample_rate() == 32.25 15 | -------------------------------------------------------------------------------- /test/test_gpio_input.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import os 3 | import time 4 | 5 | import CHIP_IO.GPIO as GPIO 6 | 7 | def teardown_module(module): 8 | GPIO.cleanup() 9 | 10 | class TestGPIOInput: 11 | def test_input(self): 12 | GPIO.setup("CSID6", GPIO.IN) 13 | #returned as an int type 14 | input_value = GPIO.input("CSID6") 15 | #value read from the file will have a \n new line 16 | value = open('/sys/class/gpio/gpio138/value').read() 17 | assert int(value) == input_value 18 | # time.sleep(30) - what is this for? 19 | GPIO.cleanup() 20 | 21 | def test_direction_readback(self): 22 | GPIO.setup("CSID6", GPIO.IN) 23 | direction = GPIO.gpio_function("CSID6") 24 | assert direction == GPIO.IN 25 | -------------------------------------------------------------------------------- /debian/control: -------------------------------------------------------------------------------- 1 | Source: chip-io 2 | Maintainer: Robert Wolterman 3 | Section: python 4 | Priority: optional 5 | Build-Depends: python-setuptools (>= 0.6b3), python-all-dev (>= 2.6.6-3), debhelper (>= 9), dh-python, 6 | python3-all (>=3.2), python3-setuptools 7 | Standards-Version: 3.9.1 8 | 9 | Package: python-chip-io 10 | Architecture: any 11 | Depends: ${misc:Depends}, ${python:Depends}, ${shlibs:Depends} 12 | Description: A module to control CHIP IO channels 13 | CHIP_IO 14 | ============================ 15 | A CHIP GPIO library 16 | 17 | Package: python3-chip-io 18 | Architecture: any 19 | Depends: ${misc:Depends}, ${python3:Depends}, ${shlibs:Depends} 20 | Description: A module to control CHIP IO channels 21 | CHIP_IO 22 | ============================ 23 | A CHIP GPIO library 24 | -------------------------------------------------------------------------------- /fix_py_compile.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2 2 | # Some Angstrom images are missing the py_compile module; get it if not 3 | # present: 4 | # Fix credit:https://github.com/alexanderhiam/PyBBIO/blob/master/setup.py 5 | import random, os 6 | python_lib_path = random.__file__.split('random')[0] 7 | if not os.path.exists(python_lib_path + 'py_compile.py'): 8 | print "py_compile module missing; installing to %spy_compile.py" %\ 9 | python_lib_path 10 | import urllib2 11 | url = "http://hg.python.org/cpython/raw-file/4ebe1ede981e/Lib/py_compile.py" 12 | py_compile = urllib2.urlopen(url) 13 | with open(python_lib_path+'py_compile.py', 'w') as f: 14 | f.write(py_compile.read()) 15 | print "testing py_compile..." 16 | try: 17 | import py_compile 18 | print "py_compile installed successfully" 19 | except Exception, e: 20 | print "*py_compile install failed, could not import" 21 | print "*Exception raised:" 22 | raise e 23 | -------------------------------------------------------------------------------- /test/integrations/spwmtest2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import CHIP_IO.SOFTPWM as PWM 4 | import CHIP_IO.GPIO as GPIO 5 | import CHIP_IO.OverlayManager as OM 6 | import time 7 | import datetime 8 | 9 | if __name__ == "__main__": 10 | # SETUP VARIABLES 11 | PWMGPIO = "XIO-P7" 12 | #PWMGPIO = "LCD-D4" 13 | COUNT = 150 14 | SLEEPTIME = 0.01 15 | 16 | time.sleep(1) 17 | 18 | # SETUP PWM 19 | try: 20 | print("PWM START") 21 | #PWM.toggle_debug() 22 | PWM.start(PWMGPIO, 50, 45, 1) 23 | 24 | # UNCOMMENT FOR CRASH 25 | print("PWM SET FREQUENCY") 26 | PWM.set_frequency(PWMGPIO, 10) 27 | 28 | # UNCOMMENT FOR CRASH 29 | print("PWM SET DUTY CYCLE") 30 | PWM.set_duty_cycle(PWMGPIO, 25) 31 | 32 | #time.sleep(COUNT*SLEEPTIME + 1) 33 | raw_input("PRESS ENTER WHEN DONE") 34 | 35 | except: 36 | raise 37 | finally: 38 | # CLEANUP 39 | print("CLEANUP") 40 | PWM.stop(PWMGPIO) 41 | PWM.cleanup() 42 | #OM.unload("PWM0") 43 | #GPIO.cleanup() 44 | 45 | 46 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /test/integrations/omtest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import CHIP_IO.OverlayManager as OM 4 | import os 5 | 6 | # ENABLE DEBUG 7 | print("ENABLING OVERLAY MANAGER DEBUG") 8 | OM.toggle_debug() 9 | 10 | # **************** PWM ******************* 11 | print("\nIS PWM ENABLED: {0}".format(OM.get_pwm_loaded())) 12 | OM.load("PWM0") 13 | print("IS PWM ENABLED: {0}".format(OM.get_pwm_loaded())) 14 | # VERIFY PWM0 EXISTS 15 | if os.path.exists('/sys/class/pwm/pwmchip0'): 16 | print("PWM DEVICE EXISTS") 17 | else: 18 | print("PWM DEVICE DID NOT LOAD PROPERLY") 19 | print("UNLOADING PWM0") 20 | OM.unload("PWM0") 21 | print("IS PWM ENABLED: {0}".format(OM.get_pwm_loaded())) 22 | 23 | # **************** SPI2 ******************* 24 | print("\nIS SPI ENABLED: {0}".format(OM.get_spi_loaded())) 25 | OM.load("SPI2") 26 | print("IS SPI ENABLED: {0}".format(OM.get_spi_loaded())) 27 | # VERIFY SPI2 EXISTS 28 | if os.listdir('/sys/class/spi_master') != "": 29 | print("SPI DEVICE EXISTS") 30 | else: 31 | print("SPI DEVICE DID NOT LOAD PROPERLY") 32 | print("UNLOADING SPI") 33 | OM.unload("SPI2") 34 | print("IS SPI ENABLED: {0}".format(OM.get_spi_loaded())) 35 | 36 | 37 | -------------------------------------------------------------------------------- /test/test_gpio_output.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | import CHIP_IO.GPIO as GPIO 4 | 5 | 6 | def teardown_module(module): 7 | GPIO.cleanup() 8 | 9 | 10 | class TestGPIOOutput: 11 | def test_output_high(self): 12 | GPIO.setup("CSID6", GPIO.OUT) 13 | GPIO.output("CSID6", GPIO.HIGH) 14 | value = open('/sys/class/gpio/gpio138/value').read() 15 | assert int(value) 16 | GPIO.cleanup() 17 | 18 | def test_output_low(self): 19 | GPIO.setup("CSID6", GPIO.OUT) 20 | GPIO.output("CSID6", GPIO.LOW) 21 | value = open('/sys/class/gpio/gpio138/value').read() 22 | assert not int(value) 23 | GPIO.cleanup() 24 | 25 | def test_direction_readback(self): 26 | GPIO.setup("CSID6", GPIO.OUT) 27 | direction = GPIO.gpio_function("CSID6") 28 | assert direction == GPIO.OUT 29 | GPIO.cleanup() 30 | 31 | def test_output_greater_than_one(self): 32 | GPIO.setup("CSID6", GPIO.OUT) 33 | GPIO.output("CSID6", 2) 34 | value = open('/sys/class/gpio/gpio138/value').read() 35 | assert int(value) 36 | GPIO.cleanup() 37 | 38 | def test_output_of_pin_not_setup(self): 39 | with pytest.raises(RuntimeError): 40 | GPIO.output("CSID7", GPIO.LOW) 41 | GPIO.cleanup() 42 | 43 | def test_output_setup_as_input(self): 44 | GPIO.setup("CSID6", GPIO.IN) 45 | with pytest.raises(RuntimeError): 46 | GPIO.output("CSID6", GPIO.LOW) 47 | GPIO.cleanup() 48 | -------------------------------------------------------------------------------- /test/integrations/lradctest.py: -------------------------------------------------------------------------------- 1 | import CHIP_IO.LRADC as ADC 2 | 3 | # == ENABLE DEBUG == 4 | print("ENABLING LRADC DEBUG OUTPUT") 5 | ADC.toggle_debug() 6 | 7 | # == SETUP == 8 | print("LRADC SETUP WITH SAMPLE RATE OF 125") 9 | ADC.setup(125) 10 | 11 | # == SCALE FACTOR == 12 | print("GETTING SCALE FACTOR") 13 | scalefactor = ADC.get_scale_factor() 14 | print(scalefactor) 15 | print("") 16 | 17 | # == ALLOWABLE SAMPLING RATES == 18 | print("GETTING ALLOWABLE SAMPLE RATES") 19 | rates = ADC.get_allowable_sample_rates() 20 | print(rates) 21 | print("IS 32.25 IN RATE TUPLE") 22 | print(ADC.SAMPLE_RATE_32P25 in rates) 23 | print("") 24 | 25 | # == CURRENT SAMPLE RATE == 26 | print("CURRENT SAMPLING RATE") 27 | crate = ADC.get_sample_rate() 28 | print(crate) 29 | print("") 30 | 31 | # == SET SAMPLE RATE == 32 | print("SETTING SAMPLE RATE TO 62.5") 33 | ADC.set_sample_rate(62.5) 34 | crate = ADC.get_sample_rate() 35 | print(crate) 36 | print("") 37 | 38 | # == CHAN 0 RAW == 39 | print("READING LRADC CHAN0 RAW") 40 | raw0 = ADC.get_chan0_raw() 41 | print(raw0) 42 | print("") 43 | 44 | # == CHAN 1 RAW == 45 | print("READING LRADC CHAN1 RAW") 46 | raw1 = ADC.get_chan1_raw() 47 | print(raw1) 48 | print("") 49 | 50 | # == CHAN 0 == 51 | print("READING LRADC CHAN0 WITH SCALE APPLIED") 52 | full0 = ADC.get_chan0() 53 | print(full0) 54 | print("") 55 | 56 | # == CHAN 1 == 57 | print("READING LRADC CHAN1 WITH SCALE APPLIED") 58 | full1 = ADC.get_chan1() 59 | print(full1) 60 | print("") 61 | 62 | # == RESET == 63 | print("RESETING SAMPLE RATE TO 250") 64 | ADC.set_sample_rate(250) 65 | 66 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # PyPi Packaging 2 | package: clean 3 | @echo " ** PACKAGING FOR PYPI **" 4 | python setup.py sdist bdist_wheel 5 | python3 setup.py bdist_wheel 6 | 7 | # PyPi Packaging 8 | package3: package 9 | @echo " ** PACKAGING FOR PYPI **" 10 | python3 setup.py bdist_wheel 11 | 12 | # PyPi Publishing 13 | publish: package package3 14 | @echo " ** UPLOADING TO PYPI **" 15 | twine upload dist/* 16 | 17 | # Clean all the things 18 | clean: 19 | @echo " ** CLEANING CHIP_IO **" 20 | rm -rf CHIP_IO.* build dist 21 | rm -f *.pyo *.pyc 22 | rm -f *.egg 23 | rm -rf __pycache__ 24 | rm -rf test/__pycache__/ 25 | rm -rf debian/python-chip-io* 26 | rm -rf debian/python3-chip-io* 27 | 28 | # Run all the tests 29 | tests: pytest2 pytest3 30 | 31 | # Run the tests with Python 2 32 | pytest2: 33 | @echo " ** RUNING CHIP_IO TESTS UNDER PYTHON 2 **" 34 | pushd test; python -m pytest; popd 35 | 36 | # Run the tests with Python 3 37 | pytest3: 38 | @echo " ** RUNING CHIP_IO TESTS UNDER PYTHON 3 **" 39 | pushd test; python3 -m pytest; popd 40 | 41 | # Build all the things 42 | build: 43 | @echo " ** BUILDING CHIP_IO: PYTHON 2 **" 44 | python setup.py build --force 45 | 46 | # Install all the things 47 | install: build 48 | @echo " ** INSTALLING CHIP_IO: PYTHON 2 **" 49 | python setup.py install --force 50 | 51 | # Build for Python 3 52 | build3: 53 | @echo " ** BUILDING CHIP_IO: PYTHON 3 **" 54 | python3 setup.py build --force 55 | 56 | # Install for Python 3 57 | install3: build3 58 | @echo " ** INSTALLING CHIP_IO: PYTHON 3 **" 59 | python3 setup.py install --force 60 | 61 | # Install for both Python 2 and 3 62 | all: install install3 63 | 64 | # Create a deb file 65 | debfile: 66 | @echo " ** BUILDING DEBIAN PACKAGES **" 67 | dpkg-buildpackage -rfakeroot -uc -b 68 | -------------------------------------------------------------------------------- /source/c_softpwm.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Brady Hurlburt 3 | 4 | Original BBIO Author Justin Cooper 5 | Modified for CHIP_IO Author Brady Hurlburt 6 | 7 | This file incorporates work covered by the following copyright and 8 | permission notice, all modified code adopts the original license: 9 | 10 | Copyright (c) 2013 Adafruit 11 | Author: Justin Cooper 12 | 13 | Permission is hereby granted, free of charge, to any person obtaining a copy of 14 | this software and associated documentation files (the "Software"), to deal in 15 | the Software without restriction, including without limitation the rights to 16 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 17 | of the Software, and to permit persons to whom the Software is furnished to do 18 | so, subject to the following conditions: 19 | 20 | The above copyright notice and this permission notice shall be included in all 21 | copies or substantial portions of the Software. 22 | 23 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 24 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 25 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 26 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 27 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 28 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 29 | SOFTWARE. 30 | */ 31 | 32 | int softpwm_start(const char *key, float duty, float freq, int polarity); 33 | int softpwm_disable(const char *key); 34 | int softpwm_set_frequency(const char *key, float freq); 35 | int softpwm_set_duty_cycle(const char *key, float duty); 36 | int softpwm_set_enable(const char *key, int enable); 37 | void softpwm_cleanup(void); 38 | -------------------------------------------------------------------------------- /source/c_softservo.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017 Robert Wolterman 3 | 4 | Using CHIP_IO SoftPWM code from Brady Hurlburt as a basis for the servo code 5 | 6 | Copyright (c) 2016 Brady Hurlburt 7 | 8 | Original BBIO Author Justin Cooper 9 | Modified for CHIP_IO Author Brady Hurlburt 10 | 11 | This file incorporates work covered by the following copyright and 12 | permission notice, all modified code adopts the original license: 13 | 14 | Copyright (c) 2013 Adafruit 15 | Author: Justin Cooper 16 | 17 | Permission is hereby granted, free of charge, to any person obtaining a copy of 18 | this software and associated documentation files (the "Software"), to deal in 19 | the Software without restriction, including without limitation the rights to 20 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 21 | of the Software, and to permit persons to whom the Software is furnished to do 22 | so, subject to the following conditions: 23 | 24 | The above copyright notice and this permission notice shall be included in all 25 | copies or substantial portions of the Software. 26 | 27 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 28 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 29 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 30 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 31 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 32 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 33 | SOFTWARE. 34 | */ 35 | 36 | int servo_start(const char *key, float angle, float range); 37 | int servo_disable(const char *key); 38 | int servo_set_range(const char *key, float range); 39 | int servo_set_angle(const char *key, float angle); 40 | void servo_cleanup(void); 41 | -------------------------------------------------------------------------------- /source/c_pwm.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Robert Wolterman 3 | 4 | Original BBIO Author Justin Cooper 5 | Modified for CHIP_IO Author Robert Wolterman 6 | 7 | This file incorporates work covered by the following copyright and 8 | permission notice, all modified code adopts the original license: 9 | 10 | Copyright (c) 2013 Adafruit 11 | Author: Justin Cooper 12 | 13 | Permission is hereby granted, free of charge, to any person obtaining a copy of 14 | this software and associated documentation files (the "Software"), to deal in 15 | the Software without restriction, including without limitation the rights to 16 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 17 | of the Software, and to permit persons to whom the Software is furnished to do 18 | so, subject to the following conditions: 19 | 20 | The above copyright notice and this permission notice shall be included in all 21 | copies or substantial portions of the Software. 22 | 23 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 24 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 25 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 26 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 27 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 28 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 29 | SOFTWARE. 30 | */ 31 | 32 | int pwm_start(const char *key, float duty, float freq, int polarity); 33 | int pwm_disable(const char *key); 34 | int pwm_set_frequency(const char *key, float freq); 35 | int pwm_set_period_ns(const char *key, unsigned long period_ns); 36 | int pwm_get_period_ns(const char *key, unsigned long *period_ns); 37 | int pwm_set_duty_cycle(const char *key, float duty); 38 | int pwm_set_pulse_width_ns(const char *key, unsigned long pulse_width_ns); 39 | int pwm_set_enable(const char *key, int enable); 40 | void pwm_cleanup(void); 41 | -------------------------------------------------------------------------------- /test/integrations/spwmtest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import CHIP_IO.SOFTPWM as SPWM 4 | import CHIP_IO.GPIO as GPIO 5 | import time 6 | import datetime 7 | import threading 8 | 9 | class SPWMReceiver(threading.Thread): 10 | def __init__(self,gpio,key,maxcount=20,sleeptime=0.5): 11 | self.gpio = gpio 12 | self.key = key 13 | self.counter = 0 14 | self.maxcount = maxcount 15 | self.sleeptime = sleeptime 16 | threading.Thread.__init__(self) 17 | 18 | def run(self): 19 | print("SETTING UP RECEIVER GPIO") 20 | self.gpio.cleanup() 21 | self.gpio.setup(self.key, self.gpio.IN) 22 | print("STARTING RECEIVE LOOP") 23 | try: 24 | while self.counter < self.maxcount: 25 | pwmval = self.gpio.input(self.key) 26 | print("SPWM VALUE: {0} @ {1}".format(pwmval, datetime.datetime.now())) 27 | time.sleep(self.sleeptime) 28 | self.counter += 1 29 | except KeyboardInterrupt: 30 | self.gpio.cleanup(self.key) 31 | 32 | if __name__ == "__main__": 33 | # SETUP VARIABLES 34 | SPWMGPIO = "XIO-P7" 35 | RECEIVERGPIO = "CSID0" 36 | COUNT = 200 37 | SLEEPTIME = 0.01 38 | 39 | # CLEANUP THE GPIO 40 | GPIO.cleanup() 41 | SPWM.cleanup() 42 | 43 | # ISSUE #16 VERIFICATION 44 | try: 45 | print("VERIFYING FIX FOR ISSUE #16, GPIO CONFIGURED THAT SPWM WANTS TO USE") 46 | GPIO.setup(SPWMGPIO, GPIO.OUT) 47 | SPWM.start(SPWMGPIO, 50, 1) 48 | except Exception as e: 49 | print("EXCEPTION: {}".format(e)) 50 | print("GPIO CLEANUP") 51 | GPIO.cleanup() 52 | 53 | # SETUP SOFTPWM 54 | print("STARTING SOFTPWM TEST") 55 | SPWM.start(SPWMGPIO, 50, 1) 56 | SPWM.set_frequency(SPWMGPIO, 2) 57 | 58 | # SETUP SOFTPWM RECEIVER 59 | rcvr = SPWMReceiver(GPIO, RECEIVERGPIO, COUNT, SLEEPTIME) 60 | rcvr.start() 61 | 62 | time.sleep(COUNT*SLEEPTIME + 1) 63 | 64 | # CLEANUP 65 | print("CLEANUP") 66 | SPWM.stop(SPWMGPIO) 67 | SPWM.cleanup() 68 | GPIO.cleanup() 69 | 70 | 71 | -------------------------------------------------------------------------------- /test/integrations/servotest.py: -------------------------------------------------------------------------------- 1 | import CHIP_IO.SERVO as SERVO 2 | import CHIP_IO.GPIO as GPIO 3 | import time 4 | import datetime 5 | import threading 6 | 7 | class ServoTestReceiver(threading.Thread): 8 | def __init__(self,gpio,key,maxcount=20,sleeptime=0.005): 9 | self.gpio = gpio 10 | self.key = key 11 | self.counter = 0 12 | self.maxcount = maxcount 13 | self.sleeptime = sleeptime 14 | self.dead = False 15 | threading.Thread.__init__(self) 16 | 17 | def kill(self): 18 | self.dead = True 19 | 20 | def run(self): 21 | print("SETTING UP RECEIVER GPIO") 22 | self.gpio.cleanup() 23 | self.gpio.setup(self.key, self.gpio.IN) 24 | print("STARTING RECEIVE LOOP") 25 | try: 26 | #while self.counter < self.maxcount: 27 | while not self.dead: 28 | pwmval = self.gpio.input(self.key) 29 | print("SERVO VALUE: {0} @ {1}".format(pwmval, datetime.datetime.now())) 30 | time.sleep(self.sleeptime) 31 | self.counter += 1 32 | except KeyboardInterrupt: 33 | self.gpio.cleanup(self.key) 34 | 35 | 36 | if __name__ == "__main__": 37 | # SETUP VARIABLES 38 | SERVOGPIO = "CSID1" #"XIO-P7" 39 | RECEIVERGPIO = "CSID7" 40 | COUNT = 120 41 | SLEEPTIME = 0.0001 42 | RANGE = 180 43 | 44 | # SETUP PWM 45 | try: 46 | print("SERVO START") 47 | SERVO.toggle_debug() 48 | SERVO.start(SERVOGPIO, 0, RANGE) 49 | 50 | # SETUP SERVO RECEIVER 51 | #rcvr = ServoTestReceiver(GPIO, RECEIVERGPIO, COUNT, SLEEPTIME) 52 | #rcvr.start() 53 | 54 | # LOOP THROUGH RANGE 55 | for i in range(-(RANGE/2),(RANGE/2),5): 56 | print("SETTING ANGLE: {0}".format(i)) 57 | SERVO.set_angle(SERVOGPIO, i) 58 | time.sleep(1) 59 | 60 | #rcvr.kill() 61 | raw_input("PRESS ENTER WHEN DONE") 62 | 63 | except: 64 | raise 65 | finally: 66 | # CLEANUP 67 | print("CLEANUP") 68 | SERVO.stop(SERVOGPIO) 69 | SERVO.cleanup(SERVOGPIO) 70 | 71 | 72 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import distribute_setup 2 | distribute_setup.use_setuptools() 3 | from setuptools import setup, Extension, find_packages 4 | 5 | classifiers = ['Development Status :: 3 - Alpha', 6 | 'Operating System :: POSIX :: Linux', 7 | 'License :: OSI Approved :: MIT License', 8 | 'Intended Audience :: Developers', 9 | 'Programming Language :: Python :: 2.7', 10 | 'Programming Language :: Python :: 3', 11 | 'Topic :: Software Development', 12 | 'Topic :: Home Automation', 13 | 'Topic :: System :: Hardware'] 14 | 15 | setup(name = 'CHIP_IO', 16 | version = '0.7.1', 17 | author = 'Robert Wolterman', 18 | author_email = 'robert.wolterman@gmail.com', 19 | description = 'A module to control CHIP IO channels', 20 | long_description = open('README.rst').read() + open('CHANGELOG.rst').read(), 21 | license = 'MIT', 22 | keywords = 'CHIP NextThingCo IO GPIO PWM ADC GR8 R8', 23 | url = 'https://github.com/xtacocorex/CHIP_IO/', 24 | classifiers = classifiers, 25 | packages = find_packages(), 26 | ext_modules = [Extension('CHIP_IO.GPIO', ['source/py_gpio.c', 'source/event_gpio.c', 'source/constants.c', 'source/common.c'], extra_compile_args=['-Wno-format-security']), 27 | Extension('CHIP_IO.PWM', ['source/py_pwm.c', 'source/c_pwm.c', 'source/constants.c', 'source/common.c'], extra_compile_args=['-Wno-format-security']), 28 | Extension('CHIP_IO.SOFTPWM', ['source/py_softpwm.c', 'source/c_softpwm.c', 'source/constants.c', 'source/common.c', 'source/event_gpio.c'], extra_compile_args=['-Wno-format-security']), 29 | Extension('CHIP_IO.SERVO', ['source/py_servo.c', 'source/c_softservo.c', 'source/constants.c', 'source/common.c', 'source/event_gpio.c'], extra_compile_args=['-Wno-format-security'])]) #, 30 | # Extension('CHIP_IO.ADC', ['source/py_adc.c', 'source/c_adc.c', 'source/constants.c', 'source/common.c'], extra_compile_args=['-Wno-format-security']), 31 | -------------------------------------------------------------------------------- /docs/utilities.md: -------------------------------------------------------------------------------- 1 | ## CHIP_IO.Utilities 2 | Import the Utilities module as follows 3 | 4 | ```python 5 | import CHIP_IO.Utilities as UT 6 | ``` 7 | 8 | ### toggle_debug() 9 | Enable/Disable the Debug 10 | 11 | * Parameters 12 | 13 | None 14 | 15 | * Returns 16 | 17 | None 18 | 19 | * Examples 20 | 21 | ```python 22 | UT.toggle_debug() 23 | ``` 24 | 25 | ### unexport_all() 26 | Function to force clean up all exported GPIO on the system 27 | 28 | * Parameters 29 | 30 | None 31 | 32 | * Returns 33 | 34 | None 35 | 36 | * Examples 37 | 38 | ```python 39 | UT.unexport_all() 40 | ``` 41 | 42 | ### is_chip_pro() 43 | Function to report to the calling script if the SBC is a CHIP or a CHIP Pro 44 | 45 | * Parameters 46 | 47 | None 48 | 49 | * Returns 50 | 51 | boolean - True for CHIP Pro, False for CHIP 52 | 53 | * Examples 54 | 55 | ```python 56 | is_chip_pro = UT.is_chip_pro() 57 | ``` 58 | 59 | ### enable_1v8_pin() 60 | Enable the 1.8V pin on the CHIP as it is disabled by default. Also sets the output to 1.8V. 61 | This only works on the CHIP. 62 | 63 | * Parameters 64 | 65 | None 66 | 67 | * Returns 68 | 69 | None 70 | 71 | * Examples 72 | 73 | ```python 74 | UT.enable_1v8_pin() 75 | ``` 76 | 77 | ### set_1v8_pin_voltage(voltage) 78 | Change the voltage of the 1.8V Pin on the CHIP. 79 | This only works on the CHIP. 80 | 81 | * Parameters 82 | 83 | voltage - 1.8, 2.0, 2.6, 3.3 84 | 85 | * Returns 86 | 87 | boolean - False on error 88 | 89 | * Examples 90 | 91 | ```python 92 | UT.set_1v8_pin_voltage(2.0) 93 | ``` 94 | 95 | 96 | ### get_1v8_pin_voltage() 97 | Get the current voltage of the 1.8V Pin on the CHIP. 98 | This only works on the CHIP. 99 | 100 | * Parameters 101 | 102 | None 103 | 104 | * Returns 105 | 106 | float - current voltage of the 1.8V Pin 107 | 108 | * Examples 109 | 110 | ```python 111 | volts = UT.get_1v8_pin_voltage() 112 | ``` 113 | 114 | ### disable_1v8_pin() 115 | Disables the 1.8V pin on the CHIP. 116 | This only works on the CHIP. 117 | 118 | * Parameters 119 | 120 | None 121 | 122 | * Returns 123 | 124 | None 125 | 126 | * Examples 127 | 128 | ```python 129 | UT.disable_1v8_pin() 130 | ``` 131 | 132 | [home](./index.md) 133 | -------------------------------------------------------------------------------- /docs/overlaymanager.md: -------------------------------------------------------------------------------- 1 | ## CHIP_IO.OverlayManager 2 | Import the OverlayManager module as follows 3 | 4 | ```python 5 | import CHIP_IO.OverlayManager as OM 6 | ``` 7 | 8 | This module requires NTC's [CHIP-dt-overlays](https://github.com/NextThingCo/CHIP-dt-overlays) to be loaded. 9 | 10 | ### toggle_debug() 11 | Enable/Disable the Debug 12 | 13 | * Parameters 14 | 15 | None 16 | 17 | * Returns 18 | 19 | None 20 | 21 | * Examples 22 | 23 | ```python 24 | OM.toggle_debug() 25 | ``` 26 | 27 | ### load(overlay, path="") 28 | Loads the overlay specified. PWM0 is not available on the CHIP Pro due to the base DTS supporting both PWM0 and PWM1 29 | 30 | * Parameters 31 | 32 | overlay - Overlay to be loaded: SPI2, PWM0, CUST 33 | path (optional) - Path to the custom compiled overlay 34 | 35 | * Returns 36 | 37 | integer - 0: Success, 1: Fail, 2: Overlay already loaded 38 | 39 | * Examples 40 | 41 | ```python 42 | resp = OM.load("SPI2") 43 | resp = OM.load("PWM0") 44 | resp = OM.load("CUST","path/to/custom.dtbo") 45 | ``` 46 | 47 | ### unload(overlay) 48 | Unloads the overlay specified. PWM0 is not available on the CHIP Pro due to the base DTS supporting both PWM0 and PWM1 49 | 50 | * Parameters 51 | 52 | overlay - Overlay to be loaded: SPI2, PWM0, CUST 53 | 54 | * Returns 55 | 56 | None 57 | 58 | * Examples 59 | 60 | ```python 61 | resp = OM.unload("SPI2") 62 | resp = OM.unload("PWM0") 63 | resp = OM.unload("CUST") 64 | ``` 65 | 66 | ### get_spi_loaded() 67 | Check to see if the SPI DTBO is loaded 68 | 69 | * Parameters 70 | 71 | None 72 | 73 | * Returns 74 | 75 | boolean 76 | 77 | * Examples 78 | 79 | ```python 80 | is_spi_loaded = OM.get_spi_loaded() 81 | ``` 82 | 83 | ### get_pwm_loaded() 84 | Check to see if the PWM0 DTBO is loaded 85 | 86 | * Parameters 87 | 88 | None 89 | 90 | * Returns 91 | 92 | boolean 93 | 94 | * Examples 95 | 96 | ```python 97 | is_pwm_loaded = OM.get_pwm_loaded() 98 | ``` 99 | 100 | ### get_custom_loaded() 101 | Check to see if the Custom DTBO is loaded 102 | 103 | * Parameters 104 | 105 | None 106 | 107 | * Returns 108 | 109 | boolean 110 | 111 | * Examples 112 | 113 | ```python 114 | is_custom_loaded = OM.get_custom_loaded() 115 | ``` 116 | 117 | [home](./index.md) 118 | -------------------------------------------------------------------------------- /docs/servo.md: -------------------------------------------------------------------------------- 1 | ## CHIP_IO.SERVO 2 | Import the SERVO module as follows 3 | 4 | ```python 5 | import CHIP_IO.SERVO as SERVO 6 | ``` 7 | 8 | ### toggle_debug() 9 | Enable/Disable the Debug 10 | 11 | * Parameters 12 | 13 | None 14 | 15 | * Examples 16 | 17 | ```python 18 | SERVO.toggle_debug() 19 | ``` 20 | 21 | ### is_chip_pro() 22 | Function to report to the calling script if the SBC is a CHIP or a CHIP Pro 23 | 24 | * Parameters 25 | 26 | None 27 | 28 | * Returns 29 | 30 | int - 1 for CHIP Pro, 0 for CHIP 31 | 32 | * Examples 33 | 34 | ```python 35 | is_chip_pro = SERVO.is_chip_pro() 36 | ``` 37 | 38 | ### start(channel, angle=0.0, range=180.0) 39 | Start the Servo 40 | 41 | * Parameters 42 | 43 | channel - Pin servo is attached to 44 | angle - initial angle of the servo (optional) 45 | range - total range of the servo in degrees (optional) 46 | 47 | * Returns 48 | 49 | None 50 | 51 | * Examples 52 | 53 | ```python 54 | SERVO.start("CSID0") 55 | SERVO.start("CSID0", 37.0) 56 | SERVO.start("CSID0", -45.0, 180.0) 57 | ``` 58 | 59 | ### stop(channel) 60 | Stop the Servo 61 | 62 | * Parameters 63 | 64 | channel - Pin servo is attached to 65 | 66 | * Returns 67 | 68 | None 69 | 70 | * Examples 71 | 72 | ```python 73 | SERVO.stop("CSID0") 74 | ``` 75 | 76 | ### set_range(channel, range) 77 | Set the range of the Servo 78 | 79 | * Parameters 80 | 81 | channel - Pin servo is attached to 82 | range - total range of the servo in degrees 83 | 84 | * Returns 85 | 86 | None 87 | 88 | * Examples 89 | 90 | ```python 91 | SERVO.set_range("CSID0", 180.0) 92 | SERVO.set_range("CSID0", 360.0) 93 | ``` 94 | 95 | ### set_angle(channel, angle) 96 | Set the angle of the Servo 97 | 98 | * Parameters 99 | 100 | channel - Pin servo is attached to 101 | angle - angle to set the servo between +/- 1/2*Range 102 | 103 | * Returns 104 | 105 | None 106 | 107 | * Examples 108 | 109 | ```python 110 | SERVO.set_angle("CSID0", -45.0) 111 | SERVO.set_angle("CSID0", 36.0) 112 | ``` 113 | 114 | ### cleanup() 115 | Cleanup all setup Servos, this will blast away every sero currently in operation 116 | 117 | * Parameters 118 | 119 | None 120 | 121 | * Returns 122 | 123 | None 124 | 125 | * Examples 126 | 127 | ```python 128 | SERVO.cleanup() 129 | ``` 130 | 131 | [home](./index.md) 132 | -------------------------------------------------------------------------------- /docs/softpwm.md: -------------------------------------------------------------------------------- 1 | ## CHIP_IO.SOFTPWM 2 | Import the SOFTPWM module as follows 3 | 4 | ```python 5 | import CHIP_IO.SOFTPWM as SPWM 6 | ``` 7 | 8 | ### toggle_debug() 9 | Enable/Disable the Debug 10 | 11 | * Parameters 12 | 13 | None 14 | 15 | * Examples 16 | 17 | ```python 18 | SPWM.toggle_debug() 19 | ``` 20 | 21 | ### is_chip_pro() 22 | Function to report to the calling script if the SBC is a CHIP or a CHIP Pro 23 | 24 | * Parameters 25 | 26 | None 27 | 28 | * Returns 29 | 30 | int - 1 for CHIP Pro, 0 for CHIP 31 | 32 | * Examples 33 | 34 | ```python 35 | is_chip_pro = SPWM.is_chip_pro() 36 | ``` 37 | 38 | ### start(channel, duty_cycle=0.0, frequency=2000.0, polarity=0) 39 | Start the Software PWM 40 | 41 | * Parameters 42 | 43 | channel - pin for software PWM is configured 44 | duty_cycle - initial duty cycle of the PWM (optional) 45 | frequency - frequency of the PWM (optional) 46 | polarity - signal polarity of the PWM (optional) 47 | 48 | * Returns 49 | 50 | None 51 | 52 | * Examples 53 | 54 | ```python 55 | SPWM.start("CSID0") 56 | SPWM.start("CSID0", 37.0) 57 | SPWM.start("CSID0", 10.0, 500.0) 58 | SPWM.start("CSID0", 50.0, 1000.0, 1) 59 | ``` 60 | 61 | ### stop(channel) 62 | Stop the Software PWM 63 | 64 | * Parameters 65 | 66 | channel - pin software PWM is configured 67 | 68 | * Returns 69 | 70 | None 71 | 72 | * Examples 73 | 74 | ```python 75 | SPWM.stop("CSID0") 76 | ``` 77 | 78 | ### set_duty_cycle(channel, duty_cycle) 79 | Set the duty cycle of the Software PWM 80 | 81 | * Parameters 82 | 83 | channel - pin software PWM is configured 84 | duty_cycle - duty cycle of the PWM (0.0 to 100.0) 85 | 86 | * Returns 87 | 88 | None 89 | 90 | * Examples 91 | 92 | ```python 93 | SPWM.set_duty_cycle("CSID0", 25.0) 94 | ``` 95 | 96 | ### set_frequency(channel, frequency) 97 | Set the frequency of the Software PWM in Hertz 98 | 99 | * Parameters 100 | 101 | channel - pin PWM is configured 102 | frequency - frequency of the PWM 103 | 104 | * Returns 105 | 106 | None 107 | 108 | * Examples 109 | 110 | ```python 111 | SPWM.set_frequency("CSID0", 450.0) 112 | ``` 113 | 114 | ### cleanup(channel) 115 | Cleanup Software PWM. If not channel input, all Software PWM will be cleaned up 116 | 117 | * Parameters 118 | 119 | channel - pin Software PWM is configured (optional) 120 | 121 | * Returns 122 | 123 | None 124 | 125 | * Examples 126 | 127 | ```python 128 | SPWM.cleanup() 129 | SPWM.cleanup("CSID0") 130 | ``` 131 | 132 | [home](./index.md) 133 | -------------------------------------------------------------------------------- /test/test_gpio_setup.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import os 3 | 4 | import CHIP_IO.GPIO as GPIO 5 | 6 | def teardown_module(module): 7 | GPIO.cleanup() 8 | 9 | class TestSetup: 10 | def test_setup_output_key(self): 11 | GPIO.setup("U14_37", GPIO.OUT) 12 | assert os.path.exists('/sys/class/gpio/gpio138') 13 | direction = open('/sys/class/gpio/gpio138/direction').read() 14 | assert direction == 'out\n' 15 | GPIO.cleanup() 16 | 17 | def test_setup_output_name(self): 18 | GPIO.setup("CSID6", GPIO.OUT) 19 | assert os.path.exists('/sys/class/gpio/gpio138') 20 | direction = open('/sys/class/gpio/gpio138/direction').read() 21 | assert direction == 'out\n' 22 | GPIO.cleanup() 23 | 24 | def test_setup_input_key(self): 25 | GPIO.setup("U14_37", GPIO.IN) 26 | assert os.path.exists('/sys/class/gpio/gpio138') 27 | direction = open('/sys/class/gpio/gpio138/direction').read() 28 | assert direction == 'in\n' 29 | GPIO.cleanup() 30 | 31 | def test_setup_input_name(self): 32 | GPIO.setup("CSID6", GPIO.IN) 33 | assert os.path.exists('/sys/class/gpio/gpio138') 34 | direction = open('/sys/class/gpio/gpio138/direction').read() 35 | assert direction == 'in\n' 36 | GPIO.cleanup() 37 | 38 | def test_setup_input_pull_up(self): 39 | GPIO.setup("U14_37", GPIO.IN, pull_up_down=GPIO.PUD_UP) 40 | assert os.path.exists('/sys/class/gpio/gpio138') 41 | direction = open('/sys/class/gpio/gpio138/direction').read() 42 | assert direction == 'in\n' 43 | GPIO.cleanup() 44 | 45 | def test_setup_input_pull_down(self): 46 | GPIO.setup("U14_37", GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 47 | assert os.path.exists('/sys/class/gpio/gpio138') 48 | direction = open('/sys/class/gpio/gpio138/direction').read() 49 | assert direction == 'in\n' 50 | GPIO.cleanup() 51 | 52 | def test_setup_cleanup(self): 53 | GPIO.setup("U14_37", GPIO.OUT) 54 | assert os.path.exists('/sys/class/gpio/gpio138') 55 | GPIO.cleanup() 56 | assert not os.path.exists('/sys/class/gpio/gpio138') 57 | 58 | def test_setup_failed_type_error(self): 59 | with pytest.raises(TypeError): 60 | GPIO.setup("U14_37", "WEIRD") 61 | GPIO.cleanup() 62 | 63 | def test_setup_failed_value_error(self): 64 | with pytest.raises(ValueError): 65 | GPIO.setup("U14_37", 3) 66 | GPIO.cleanup() 67 | 68 | def test_setup_expanded_gpio(self): 69 | GPIO.setup("XIO-P1", GPIO.OUT) 70 | base = GPIO.get_gpio_base() + 1 71 | gfile = '/sys/class/gpio/gpio%d' % base 72 | assert os.path.exists(gfile) 73 | GPIO.cleanup() 74 | assert not os.path.exists(gfile) 75 | 76 | -------------------------------------------------------------------------------- /test/integrations/pwmtest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import CHIP_IO.PWM as PWM 4 | import CHIP_IO.GPIO as GPIO 5 | import CHIP_IO.OverlayManager as OM 6 | import time 7 | import datetime 8 | import threading 9 | 10 | class PWMReceiver(threading.Thread): 11 | def __init__(self,gpio,key,maxcount=20,sleeptime=0.5): 12 | self.gpio = gpio 13 | self.key = key 14 | self.counter = 0 15 | self.maxcount = maxcount 16 | self.sleeptime = sleeptime 17 | threading.Thread.__init__(self) 18 | 19 | def run(self): 20 | print("SETTING UP RECEIVER GPIO") 21 | self.gpio.cleanup() 22 | self.gpio.setup(self.key, self.gpio.IN) 23 | print("STARTING RECEIVE LOOP") 24 | try: 25 | while self.counter < self.maxcount: 26 | pwmval = self.gpio.input(self.key) 27 | print("PWM VALUE: {0} @ {1}".format(pwmval, datetime.datetime.now())) 28 | time.sleep(self.sleeptime) 29 | self.counter += 1 30 | except KeyboardInterrupt: 31 | self.gpio.cleanup(self.key) 32 | 33 | def PrintPwmData(): 34 | print("PRINTING PWM SYSFS DATA") 35 | f = open("/sys/class/pwm/pwmchip0/pwm0/enable") 36 | print("PWM0 ENABLE:\t{}".format(f.readline())) 37 | f.close() 38 | f = open("/sys/class/pwm/pwmchip0/pwm0/period") 39 | print("PWM0 PERIOD:\t{}".format(f.readline())) 40 | f.close() 41 | f = open("/sys/class/pwm/pwmchip0/pwm0/duty_cycle") 42 | print("PWM0 DUTY CYCLE:\t{}".format(f.readline())) 43 | f.close() 44 | f = open("/sys/class/pwm/pwmchip0/pwm0/polarity") 45 | print("PWM0 POLARITY:\t{}".format(f.readline())) 46 | f.close() 47 | 48 | if __name__ == "__main__": 49 | # SETUP VARIABLES 50 | PWMGPIO = "PWM0" 51 | RECEIVERGPIO = "CSID0" 52 | COUNT = 150 53 | SLEEPTIME = 0.01 54 | 55 | # LOAD THE PWM OVERLAY 56 | print("LOADING PWM OVERLAY") 57 | OM.load("PWM0") 58 | 59 | time.sleep(1) 60 | 61 | # CLEANUP THE GPIO 62 | #GPIO.cleanup() 63 | #PWM.cleanup() 64 | 65 | # SETUP PWM 66 | try: 67 | print("PWM START") 68 | PWM.toggle_debug() 69 | PWM.start(PWMGPIO, 15, 50, 1) 70 | PrintPwmData() 71 | 72 | # UNCOMMENT FOR CRASH 73 | #print("PWM SET FREQUENCY") 74 | #PWM.set_frequency(PWMGPIO, 200) 75 | #PrintPwmData() 76 | 77 | # UNCOMMENT FOR CRASH 78 | #print("PWM SET DUTY CYCLE") 79 | #PWM.set_duty_cycle(PWMGPIO, 25) 80 | #PrintPwmData() 81 | 82 | # SETUP PWM RECEIVER 83 | #rcvr = PWMReceiver(GPIO, RECEIVERGPIO, COUNT, SLEEPTIME) 84 | #rcvr.start() 85 | 86 | #time.sleep(COUNT*SLEEPTIME + 1) 87 | raw_input("PRESS ENTER WHEN DONE") 88 | 89 | except: 90 | raise 91 | finally: 92 | # CLEANUP 93 | print("CLEANUP") 94 | PWM.stop(PWMGPIO) 95 | PWM.cleanup() 96 | #OM.unload("PWM0") 97 | #GPIO.cleanup() 98 | 99 | 100 | -------------------------------------------------------------------------------- /source/event_gpio.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Robert Wolterman 3 | 4 | Original BBIO Author Justin Cooper 5 | Modified for CHIP_IO Author Robert Wolterman 6 | 7 | This file incorporates work covered by the following copyright and 8 | permission notice, all modified code adopts the original license: 9 | 10 | Copyright (c) 2013 Adafruit 11 | 12 | Original RPi.GPIO Author Ben Croston 13 | Modified for BBIO Author Justin Cooper 14 | 15 | This file incorporates work covered by the following copyright and 16 | permission notice, all modified code adopts the original license: 17 | 18 | Copyright (c) 2013 Ben Croston 19 | 20 | Permission is hereby granted, free of charge, to any person obtaining a copy of 21 | this software and associated documentation files (the "Software"), to deal in 22 | the Software without restriction, including without limitation the rights to 23 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 24 | of the Software, and to permit persons to whom the Software is furnished to do 25 | so, subject to the following conditions: 26 | 27 | The above copyright notice and this permission notice shall be included in all 28 | copies or substantial portions of the Software. 29 | 30 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 31 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 32 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 33 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 34 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 35 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 36 | SOFTWARE. 37 | */ 38 | 39 | #include 40 | 41 | #define NO_EDGE 0 42 | #define RISING_EDGE 1 43 | #define FALLING_EDGE 2 44 | #define BOTH_EDGE 3 45 | 46 | #define INPUT 0 47 | #define OUTPUT 1 48 | #define ALT0 4 49 | 50 | #define HIGH 1 51 | #define LOW 0 52 | 53 | #define MAX_FILENAME 50 54 | 55 | #define PUD_OFF 0 56 | #define PUD_DOWN 1 57 | #define PUD_UP 2 58 | 59 | extern uint8_t *memmap; 60 | 61 | int map_pio_memory(void); 62 | int gpio_get_pud(int port, int pin); 63 | int gpio_set_pud(int port, int pin, uint8_t value); 64 | 65 | int gpio_export(int gpio); 66 | int gpio_unexport(int gpio); 67 | void exports_cleanup(void); 68 | int gpio_set_direction(int gpio, unsigned int in_flag); 69 | int gpio_get_direction(int gpio, unsigned int *value); 70 | int gpio_set_value(int gpio, unsigned int value); 71 | int gpio_get_value(int gpio, unsigned int *value); 72 | int gpio_get_more(int gpio, int bits, unsigned int *value); 73 | int fd_lookup(int gpio); 74 | int open_value_file(int gpio); 75 | 76 | int fde_lookup(int gpio); 77 | int open_edge_file(int gpio); 78 | int gpio_set_edge(int gpio, unsigned int edge); 79 | int gpio_get_edge(int gpio); 80 | int add_edge_detect(int gpio, unsigned int edge); 81 | void remove_edge_detect(int gpio); 82 | int add_edge_callback(int gpio, int edge, void (*func)(int gpio, void* data), void* data); 83 | int event_detected(int gpio); 84 | int gpio_event_add(int gpio); 85 | int gpio_event_remove(int gpio); 86 | int gpio_is_evented(int gpio); 87 | int event_initialise(void); 88 | void event_cleanup(void); 89 | int blocking_wait_for_edge(int gpio, unsigned int edge, int timeout); 90 | -------------------------------------------------------------------------------- /source/constants.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Robert Wolterman 3 | 4 | Original BBIO Author Justin Cooper 5 | Modified for CHIP_IO Author Robert Wolterman 6 | 7 | This file incorporates work covered by the following copyright and 8 | permission notice, all modified code adopts the original license: 9 | 10 | Copyright (c) 2013 Adafruit 11 | 12 | Original RPi.GPIO Author Ben Croston 13 | Modified for BBIO Author Justin Cooper 14 | 15 | This file incorporates work covered by the following copyright and 16 | permission notice, all modified code adopts the original license: 17 | 18 | Copyright (c) 2013 Ben Croston 19 | 20 | Permission is hereby granted, free of charge, to any person obtaining a copy of 21 | this software and associated documentation files (the "Software"), to deal in 22 | the Software without restriction, including without limitation the rights to 23 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 24 | of the Software, and to permit persons to whom the Software is furnished to do 25 | so, subject to the following conditions: 26 | 27 | The above copyright notice and this permission notice shall be included in all 28 | copies or substantial portions of the Software. 29 | 30 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 31 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 32 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 33 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 34 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 35 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 36 | SOFTWARE. 37 | */ 38 | 39 | #include "Python.h" 40 | #include "constants.h" 41 | #include "event_gpio.h" 42 | #include "common.h" 43 | 44 | void define_constants(PyObject *module) 45 | { 46 | high = Py_BuildValue("i", HIGH); 47 | PyModule_AddObject(module, "HIGH", high); 48 | 49 | low = Py_BuildValue("i", LOW); 50 | PyModule_AddObject(module, "LOW", low); 51 | 52 | output = Py_BuildValue("i", OUTPUT); 53 | PyModule_AddObject(module, "OUT", output); 54 | 55 | input = Py_BuildValue("i", INPUT); 56 | PyModule_AddObject(module, "IN", input); 57 | 58 | alt0 = Py_BuildValue("i", ALT0); 59 | PyModule_AddObject(module, "ALT0", alt0); 60 | 61 | pud_off = Py_BuildValue("i", PUD_OFF); 62 | PyModule_AddObject(module, "PUD_OFF", pud_off); 63 | 64 | pud_up = Py_BuildValue("i", PUD_UP); 65 | PyModule_AddObject(module, "PUD_UP", pud_up); 66 | 67 | pud_down = Py_BuildValue("i", PUD_DOWN); 68 | PyModule_AddObject(module, "PUD_DOWN", pud_down); 69 | 70 | rising_edge = Py_BuildValue("i", RISING_EDGE); 71 | PyModule_AddObject(module, "RISING", rising_edge); 72 | 73 | falling_edge = Py_BuildValue("i", FALLING_EDGE); 74 | PyModule_AddObject(module, "FALLING", falling_edge); 75 | 76 | both_edge = Py_BuildValue("i", BOTH_EDGE); 77 | PyModule_AddObject(module, "BOTH", both_edge); 78 | 79 | unknown = Py_BuildValue("i", MODE_UNKNOWN); 80 | PyModule_AddObject(module, "UNKNOWN", unknown); 81 | 82 | board = Py_BuildValue("i", BOARD); 83 | PyModule_AddObject(module, "BOARD", board); 84 | 85 | bcm = Py_BuildValue("i", BCM); 86 | PyModule_AddObject(module, "BCM", bcm); 87 | 88 | version = Py_BuildValue("s", "0.7.1"); 89 | PyModule_AddObject(module, "VERSION", version); 90 | } 91 | -------------------------------------------------------------------------------- /docs/pwm.md: -------------------------------------------------------------------------------- 1 | ## CHIP_IO.PWM 2 | Import the PWM module as follows 3 | 4 | ```python 5 | import CHIP_IO.PWM as PWM 6 | ``` 7 | 8 | For the CHIP, this requires the PWM0 DTBO loaded via the OverlayManager or other means. 9 | For the CHIP, PWM1 is unavaiable 10 | For the CHIP Pro, PWM0 and PWM1 are setup in the base DTB by default 11 | 12 | ### toggle_debug() 13 | Enable/Disable the Debug 14 | 15 | * Parameters 16 | 17 | None 18 | 19 | * Examples 20 | 21 | ```python 22 | PWM.toggle_debug() 23 | ``` 24 | 25 | ### is_chip_pro() 26 | Function to report to the calling script if the SBC is a CHIP or a CHIP Pro 27 | 28 | * Parameters 29 | 30 | None 31 | 32 | * Returns 33 | 34 | int - 1 for CHIP Pro, 0 for CHIP 35 | 36 | * Examples 37 | 38 | ```python 39 | is_chip_pro = PWM.is_chip_pro() 40 | ``` 41 | 42 | ### start(channel, duty_cycle=0.0, frequency=2000.0, polarity=0) 43 | Start the Software PWM 44 | 45 | * Parameters 46 | 47 | channel - pin for software PWM is configured 48 | duty_cycle - initial duty cycle of the PWM (optional) 49 | frequency - frequency of the PWM (optional) 50 | polarity - signal polarity of the PWM (optional) 51 | 52 | * Returns 53 | 54 | None 55 | 56 | * Examples 57 | 58 | ```python 59 | PWM.start("PWM0") 60 | PWM.start("PWM0", 37.0) 61 | PWM.start("PWM0", 10.0, 500.0) 62 | PWM.start("PWM0", 50.0, 1000.0, 1) 63 | ``` 64 | 65 | ### stop(channel) 66 | Stop the PWM 67 | 68 | * Parameters 69 | 70 | channel - pin PWM is configured 71 | 72 | * Returns 73 | 74 | None 75 | 76 | * Examples 77 | 78 | ```python 79 | PWM.stop("PWM0") 80 | ``` 81 | 82 | ### set_duty_cycle(channel, duty_cycle) 83 | Set the duty cycle of the PWM 84 | 85 | * Parameters 86 | 87 | channel - pin PWM is configured 88 | duty_cycle - duty cycle of the PWM (0.0 to 100.0) 89 | 90 | * Returns 91 | 92 | None 93 | 94 | * Examples 95 | 96 | ```python 97 | PWM.set_duty_cycle("PWM0", 25.0) 98 | ``` 99 | 100 | ### set_pulse_width_ns(channel, pulse_width_ns) 101 | Set the width of the PWM pulse in nano seconds 102 | 103 | * Parameters 104 | 105 | channel - pin PWM is configured 106 | pulse_width_ns - pulse width of the PWM in nanoseconds 107 | 108 | * Returns 109 | 110 | None 111 | 112 | * Examples 113 | 114 | ```python 115 | PWM.set_pulse_width_ns("PWM0", 2500.0) 116 | ``` 117 | 118 | ### set_frequency(channel, frequency) 119 | Set the frequency of the PWM in Hertz 120 | 121 | * Parameters 122 | 123 | channel - pin software PWM is configured 124 | frequency - frequency of the PWM 125 | 126 | * Returns 127 | 128 | None 129 | 130 | * Examples 131 | 132 | ```python 133 | PWM.set_frequency("PWM0", 450.0) 134 | ``` 135 | 136 | ### set_period_ns(channel, pulse_width_ns) 137 | Set the period of the PWM pulse in nano seconds 138 | 139 | * Parameters 140 | 141 | channel - pin PWM is configured 142 | period_ns - period of the PWM in nanoseconds 143 | 144 | * Returns 145 | 146 | None 147 | 148 | * Examples 149 | 150 | ```python 151 | PWM.set_period_ns("PWM0", 130.0) 152 | ``` 153 | 154 | ### cleanup(channel) 155 | Cleanup PWM. If not channel input, all PWM will be cleaned up 156 | 157 | * Parameters 158 | 159 | channel - pin PWM is configured (optional) 160 | 161 | * Returns 162 | 163 | None 164 | 165 | * Examples 166 | 167 | ```python 168 | PWM.cleanup() 169 | PWM.cleanup("PWM0") 170 | ``` 171 | 172 | [home](./index.md) 173 | -------------------------------------------------------------------------------- /docs/lradc.md: -------------------------------------------------------------------------------- 1 | ## CHIP_IO.LRADC 2 | The LRADC module handles interfacing with the onboard 6-Bit, 2V tolerant ADC in the R8/GR8. 3 | 4 | Import the LRADC module as follows 5 | 6 | ```python 7 | import CHIP_IO.LRADC as LRADC 8 | ``` 9 | 10 | ### toggle_debug() 11 | Enable/Disable the Debug 12 | 13 | * Parameters 14 | 15 | None 16 | 17 | * Returns 18 | 19 | None 20 | 21 | * Examples 22 | 23 | ```python 24 | LRADC.toggle_debug() 25 | ``` 26 | 27 | ### get_device_exist() 28 | Check to see if the LRADC device exists 29 | 30 | * Parameters 31 | 32 | None 33 | 34 | * Returns 35 | 36 | boolean - True if LRADC is enabled, False is LRADC is disabled 37 | 38 | * Examples 39 | 40 | ```python 41 | LRADC.get_device_exist() 42 | ``` 43 | 44 | ### setup(rate=250) 45 | Setup the LRADC, defaults to a sampling rate of 250. 46 | 47 | * Parameters 48 | 49 | rate (optional) - Sampling rate of the LRADC: 32.25, 62.5, 125, 250 50 | 51 | * Returns 52 | 53 | boolean - True if LRADC is enabled, False is LRADC is disabled 54 | 55 | * Examples 56 | 57 | ```python 58 | LRADC.setup() 59 | LRADC.setup(32.25) 60 | ``` 61 | 62 | ### get_scale_factor() 63 | Get the scaling factor applied to raw values from the LRADC 64 | 65 | * Parameters 66 | 67 | None 68 | 69 | * Returns 70 | 71 | float - scale factor applied to the LRADC Raw data 72 | 73 | * Examples 74 | 75 | ```python 76 | factor = LRADC.get_scale_factor() 77 | print(factor) 78 | ``` 79 | 80 | ### get_allowable_sample_rates() 81 | Get the allowable sample rates for the LRADC 82 | 83 | * Parameters 84 | 85 | None 86 | 87 | * Returns 88 | 89 | tuple - sampling rates of the LRADC 90 | 91 | * Examples 92 | 93 | ```python 94 | rates = LRADC.get_allowable_sample_rates() 95 | print(rates) 96 | ``` 97 | 98 | ### set_sample_rate(rate) 99 | Set the current sample rates for the LRADC 100 | 101 | * Parameters 102 | 103 | rate - Sample rate, only rates allowable by the LRADC 104 | 105 | * Returns 106 | 107 | float - current sampling rate of the LRADC 108 | 109 | * Examples 110 | 111 | ```python 112 | curr_rate = LRADC.set_sample_rate(125.0) 113 | ``` 114 | 115 | ### get_sample_rate() 116 | Get the current sample rates for the LRADC 117 | 118 | * Parameters 119 | 120 | None 121 | 122 | * Returns 123 | 124 | float - current sampling rate of the LRADC 125 | 126 | * Examples 127 | 128 | ```python 129 | curr_rate = LRADC.get_sample_rate() 130 | ``` 131 | 132 | ### get_chan0_raw() 133 | Get the raw value for LRADC Channel 0 134 | 135 | * Parameters 136 | 137 | None 138 | 139 | * Returns 140 | 141 | float - current raw value of LRADC Channel 0 142 | 143 | * Examples 144 | 145 | ```python 146 | dat = LRADC.get_chan0_raw() 147 | ``` 148 | 149 | ### get_chan1_raw() 150 | Get the raw value for LRADC Channel 1 151 | 152 | * Parameters 153 | 154 | None 155 | 156 | * Returns 157 | 158 | float - current raw value of LRADC Channel 1 159 | 160 | * Examples 161 | 162 | ```python 163 | dat = LRADC.get_chan1_raw() 164 | ``` 165 | 166 | ### get_chan0() 167 | Get the value for LRADC Channel 0 168 | 169 | * Parameters 170 | 171 | None 172 | 173 | * Returns 174 | 175 | float - current value of LRADC Channel 0 176 | 177 | * Examples 178 | 179 | ```python 180 | dat = LRADC.get_chan0() 181 | ``` 182 | 183 | ### get_chan1 184 | Get the value for LRADC Channel 1 185 | 186 | * Parameters 187 | 188 | None 189 | 190 | * Returns 191 | 192 | float - current value of LRADC Channel 1 193 | 194 | * Examples 195 | 196 | ```python 197 | dat = LRADC.get_chan1() 198 | ``` 199 | 200 | [home](./index.md) 201 | -------------------------------------------------------------------------------- /test/test_softpwm_setup.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import os 3 | 4 | import CHIP_IO.SOFTPWM as PWM 5 | import CHIP_IO.GPIO as GPIO 6 | 7 | 8 | def teardown_module(module): 9 | PWM.cleanup() 10 | 11 | 12 | class TestSoftpwmSetup: 13 | 14 | def setup_method(self, test_method): 15 | PWM.cleanup() 16 | 17 | def test_start_pwm(self): 18 | PWM.start("XIO-P7", 50, 10) 19 | base = GPIO.get_gpio_base() + 7 20 | gfile = '/sys/class/gpio/gpio%d' % base 21 | assert os.path.exists(gfile) 22 | direction = open(gfile + '/direction').read() 23 | assert(direction == 'out\n') 24 | PWM.cleanup() 25 | 26 | def test_pwm_start_invalid_pwm_key(self): 27 | with pytest.raises(ValueError): 28 | PWM.start("P8_25", -1) 29 | 30 | def test_pwm_start_invalid_duty_cycle_negative(self): 31 | with pytest.raises(ValueError): 32 | PWM.start("XIO-P7", -1) 33 | 34 | def test_pwm_start_valid_duty_cycle_min(self): 35 | # testing an exception isn't thrown 36 | PWM.start("XIO-P7", 0) 37 | PWM.cleanup() 38 | 39 | def test_pwm_start_valid_duty_cycle_max(self): 40 | # testing an exception isn't thrown 41 | PWM.start("XIO-P7", 100) 42 | PWM.cleanup() 43 | 44 | def test_pwm_start_invalid_duty_cycle_high(self): 45 | with pytest.raises(ValueError): 46 | PWM.start("XIO-P7", 101) 47 | 48 | def test_pwm_start_invalid_duty_cycle_string(self): 49 | with pytest.raises(TypeError): 50 | PWM.start("XIO-P7", "1") 51 | 52 | def test_pwm_start_invalid_frequency_negative(self): 53 | with pytest.raises(ValueError): 54 | PWM.start("XIO-P7", 0, -1) 55 | 56 | def test_pwm_start_invalid_frequency_string(self): 57 | with pytest.raises(TypeError): 58 | PWM.start("XIO-P7", 0, "1") 59 | 60 | def test_pwm_start_negative_polarity(self): 61 | with pytest.raises(ValueError): 62 | PWM.start("XIO-P7", 0, 100, -1) 63 | 64 | def test_pwm_start_invalid_positive_polarity(self): 65 | with pytest.raises(ValueError): 66 | PWM.start("XIO-P7", 0, 100, 2) 67 | 68 | def test_pwm_start_invalid_polarity_type(self): 69 | with pytest.raises(TypeError): 70 | PWM.start("XIO-P7", 0, 100, "1") 71 | 72 | def test_pwm_duty_cycle_non_setup_key(self): 73 | with pytest.raises(RuntimeError): 74 | PWM.set_duty_cycle("XIO-P7", 100) 75 | PWM.cleanup() 76 | 77 | def test_pwm_duty_cycle_invalid_key(self): 78 | with pytest.raises(ValueError): 79 | PWM.set_duty_cycle("P9_15", 100) 80 | PWM.cleanup() 81 | 82 | def test_pwm_duty_cycle_invalid_value_high(self): 83 | PWM.start("XIO-P7", 0) 84 | with pytest.raises(ValueError): 85 | PWM.set_duty_cycle("XIO-P7", 101) 86 | PWM.cleanup() 87 | 88 | def test_pwm_duty_cycle_invalid_value_negative(self): 89 | PWM.start("XIO-P7", 0) 90 | with pytest.raises(ValueError): 91 | PWM.set_duty_cycle("XIO-P7", -1) 92 | PWM.cleanup() 93 | 94 | def test_pwm_duty_cycle_invalid_value_string(self): 95 | PWM.start("XIO-P7", 0) 96 | with pytest.raises(TypeError): 97 | PWM.set_duty_cycle("XIO-P7", "a") 98 | PWM.cleanup() 99 | 100 | def test_pwm_frequency_invalid_value_negative(self): 101 | PWM.start("XIO-P7", 0) 102 | with pytest.raises(ValueError): 103 | PWM.set_frequency("XIO-P7", -1) 104 | PWM.cleanup() 105 | 106 | def test_pwm_frequency_invalid_value_string(self): 107 | PWM.start("XIO-P7", 0) 108 | with pytest.raises(TypeError): 109 | PWM.set_frequency("XIO-P7", "11") 110 | PWM.cleanup() 111 | 112 | def test_stop_pwm(self): 113 | pass 114 | -------------------------------------------------------------------------------- /debian/changelog: -------------------------------------------------------------------------------- 1 | chip-io (0.7.1-1) unstable; urgency=low 2 | 3 | * Merged PR#79 and#80 4 | * Added logging to tell user of the 1 second sleep before retry on setting gpio direction 5 | 6 | -- Robert Wolterman Sun, 12 Nov 2017 07:40:00 -0600 7 | 8 | chip-io (0.7.0-1) unstable; urgency=low 9 | 10 | * Added ability to specify GPIO only as a number, this doesn't work for PWM/SPWM/LRADC/SERVO 11 | 12 | -- Robert Wolterman Wed, 13 Sep 2017 09:51:00 -0600 13 | 14 | chip-io (0.6.2-1) unstable; urgency=low 15 | 16 | * Implementation for number 77 ability to push up binary pypi 17 | * Implementation for number 75 wait for edge timeout 18 | 19 | -- Robert Wolterman Sun, 03 Sep 2017 21:34:00 -0600 20 | 21 | chip-io (0.6.1-1) unstable; urgency=low 22 | 23 | * Fixing implementation for #76 24 | 25 | -- Robert Wolterman Wed, 09 Aug 2017 23:09:00 -0600 26 | 27 | chip-io (0.6.0-1) unstable; urgency=low 28 | 29 | * Random comment cleanup 30 | * Implement fix for #76 31 | * API documentation added 32 | * Closing #74 33 | 34 | -- Robert Wolterman Wed, 09 Aug 2017 22:50:00 -0600 35 | 36 | chip-io (0.5.9-1) unstable; urgency=low 37 | 38 | * Merged PR#70 to enable the underlying C code to be used properly in C based code 39 | * Updated README to add missing pins on the CHIP Pro that are available as GPIO 40 | * Updated README to denote pins that are available for Edge Detection 41 | 42 | -- Robert Wolterman Tue, 08 Jun 2017 20:03:00 -0600 43 | 44 | chip-io (0.5.8-1) unstable; urgency=low 45 | 46 | * Added 3 pins for the CHIP Pro as allowable for setting callbacks and edge 47 | detection to close out Issue #68 48 | 49 | -- Robert Wolterman Tue, 02 May 2017 22:43:00 -0600 50 | 51 | chip-io (0.5.7-1) unstable; urgency=low 52 | 53 | * Added the I2S pins on the CHIP Pro as GPIO capable 54 | * Added per PWM/SoftPWM cleanup per Issue #64 55 | 56 | -- Robert Wolterman Mon, 01 May 2017 22:47:00 -0600 57 | 58 | chip-io (0.5.6-1) unstable; urgency=low 59 | 60 | * Fix for Issue #63 where re-setting up a pin wasn't lining up with RPi.GPIO standards. Calling setup after the first time will now update direction. 61 | * README updates to point out the direction() function since that was missing 62 | 63 | -- Robert Wolterman Mon, 20 Mar 2017 23:04:00 -0600 64 | 65 | chip-io (0.5.5-1) unstable; urgency=low 66 | 67 | * Fix for Issue #62 where using alternate name of an XIO would cause a segfault due to trying to set pull up/down resistor setting 68 | 69 | -- Robert Wolterman Mon, 6 Mar 2017 17:02:00 -0600 70 | 71 | chip-io (0.5.4-1) unstable; urgency=low 72 | 73 | * Re-enabled the polarity setting for PWM based upon Issue #61 74 | * Fixed a 1 letter bug was trying to write inverted to polarity when it wants inversed (such facepalm) 75 | * Cleaned up the polarity setting code to work when PWM is not enabled 76 | * Fixed the unit test for pwm to verify we can set polarity 77 | 78 | -- Robert Wolterman Sat, 4 Mar 2017 20:46:00 -0600 79 | 80 | chip-io (0.5.3-1) unstable; urgency=low 81 | 82 | * Fixes to the PWM pytest 83 | * Added pytest for LRADC and Utilities 84 | * Makefile updates for all the things 85 | 86 | -- Robert Wolterman Sun, 26 Feb 2017 20:46:00 -0600 87 | 88 | chip-io (0.5.2-1) unstable; urgency=low 89 | 90 | * Updating Utilities to determine CHIP Pro better 91 | * Updating Utilities to only run CHIP appropriate code on the CHIP and not CHIP Pro 92 | * Updated README 93 | 94 | -- Robert Wolterman Sun, 26 Feb 2017 13:56:00 -0600 95 | 96 | chip-io (0.5.0-1) unstable; urgency=low 97 | 98 | * CHIP Pro support for PWM1, reduced GPIO capability 99 | * New is_chip_pro() in each of the PWM, GPIO, SoftPWM, and Servo modules 100 | * Updated README 101 | 102 | -- Robert Wolterman Sat, 25 Feb 2017 19:00:00 -0600 103 | 104 | chip-io (0.4.0-1) unstable; urgency=low 105 | 106 | * source package automatically created by stdeb 0.8.2 107 | 108 | -- Robert Wolterman Sat, 18 Feb 2017 23:58:48 +0000 109 | -------------------------------------------------------------------------------- /source/common.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Robert Wolterman 3 | 4 | Original BBIO Author Justin Cooper 5 | Modified for CHIP_IO Author Robert Wolterman 6 | 7 | This file incorporates work covered by the following copyright and 8 | permission notice, all modified code adopts the original license: 9 | 10 | Copyright (c) 2013 Adafruit 11 | 12 | Original RPi.GPIO Author Ben Croston 13 | Modified for BBIO Author Justin Cooper 14 | 15 | This file incorporates work covered by the following copyright and 16 | permission notice, all modified code adopts the original license: 17 | 18 | Copyright (c) 2013 Ben Croston 19 | 20 | Permission is hereby granted, free of charge, to any person obtaining a copy of 21 | this software and associated documentation files (the "Software"), to deal in 22 | the Software without restriction, including without limitation the rights to 23 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 24 | of the Software, and to permit persons to whom the Software is furnished to do 25 | so, subject to the following conditions: 26 | 27 | The above copyright notice and this permission notice shall be included in all 28 | copies or substantial portions of the Software. 29 | 30 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 31 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 32 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 33 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 34 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 35 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 36 | SOFTWARE. 37 | */ 38 | 39 | #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) 40 | 41 | // See http://blog.geeky-boy.com/2016/06/of-compiler-warnings-and-asserts-in.html 42 | #define ASSRT(cond_expr) do { \ 43 | if (!(cond_expr)) { \ 44 | fprintf(stderr, "ASSRT failed at %s:%d (%s)\n", __FILE__, __LINE__, #cond_expr); \ 45 | fflush(stderr); \ 46 | abort(); \ 47 | } } while (0) 48 | 49 | // See http://blog.geeky-boy.com/2016/06/snprintf-bug-detector-or-bug-preventer.html 50 | #define BUF2SMALL(b) do {\ 51 | ASSRT(strnlen(b, sizeof(b)) < sizeof(b)-1);\ 52 | } while (0) 53 | 54 | #define MODE_UNKNOWN -1 55 | #define BOARD 10 56 | #define BCM 11 57 | #define CHIP 0 58 | #define CHIPPRO 1 59 | #define BOTH 2 60 | 61 | // In the pins_t structure, the "base_method" field tells how 62 | // the "gpio" field should be interpreted. 63 | #define BASE_METHOD_AS_IS 1 /* use the gpio value directly */ 64 | #define BASE_METHOD_XIO 2 /* add the gpio value to the XIO base */ 65 | #define SPWM_ENABLED 1 /* pin able to be used by software pwm */ 66 | #define SPWM_DISABLED 0 /* pin unable to be used by software pwm */ 67 | 68 | typedef struct pins_t { 69 | const char *name; 70 | const char *altname; /* alternate name as referenced on pocketchip pin header */ 71 | const char *key; 72 | //const char *altkey; /* alternate key for chip pro */ 73 | int gpio; /* port number to use under /sys/class/gpio */ 74 | int base_method; /* modifier for port number; see BASE_METHOD_... */ 75 | int pwm_mux_mode; /* pwm pin */ 76 | int ain; /* analog pin */ 77 | int sbc_type; /* which sbc pin is allowed */ 78 | } pins_t; 79 | 80 | 81 | struct dyn_int_array_s { 82 | int num_elements; 83 | int *content; 84 | }; 85 | typedef struct dyn_int_array_s dyn_int_array_t; 86 | 87 | #define FILENAME_BUFFER_SIZE 128 88 | 89 | extern int setup_error; 90 | extern int module_setup; 91 | extern int DEBUG; 92 | 93 | int get_xio_base(void); 94 | int is_this_chippro(void); 95 | int gpio_number(pins_t *pin); 96 | int gpio_pud_capable(pins_t *pin); 97 | int lookup_gpio_by_number(const char *num); 98 | int lookup_gpio_by_key(const char *key); 99 | int lookup_gpio_by_name(const char *name); 100 | int lookup_gpio_by_altname(const char *altname); 101 | int lookup_pud_capable_by_key(const char *key); 102 | int lookup_pud_capable_by_name(const char *name); 103 | int lookup_pud_capable_by_altname(const char *altname); 104 | int lookup_ain_by_key(const char *key); 105 | int lookup_ain_by_name(const char *name); 106 | int copy_key_by_key(const char *input_key, char *key); 107 | int copy_pwm_key_by_key(const char *input_key, char *key); 108 | int get_key_by_name(const char *name, char *key); 109 | int get_pwm_key_by_name(const char *name, char *key); 110 | int get_gpio_number(const char *key, int *gpio); 111 | int get_key(const char *input, char *key); 112 | int get_pwm_key(const char *input, char *key); 113 | int get_adc_ain(const char *key, unsigned int *ain); 114 | int build_path(const char *partial_path, const char *prefix, char *full_path, size_t full_path_len); 115 | void dyn_int_array_set(dyn_int_array_t **in_array, int i, int val, int initial_val); 116 | int dyn_int_array_get(dyn_int_array_t **in_array, int i, int initial_val); 117 | void dyn_int_array_delete(dyn_int_array_t **in_array); 118 | void clear_error_msg(void); 119 | char *get_error_msg(void); 120 | void add_error_msg(char *msg); 121 | void toggle_debug(void); 122 | int compute_port_pin(const char *key, int gpio, int *port, int *pin); 123 | int gpio_allowed(int gpio); 124 | int pwm_allowed(const char *key); 125 | -------------------------------------------------------------------------------- /CHIP_IO/Utilities.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2016 Robert Wolterman 2 | # 3 | # Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | # this software and associated documentation files (the "Software"), to deal in 5 | # the Software without restriction, including without limitation the rights to 6 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 7 | # of the Software, and to permit persons to whom the Software is furnished to do 8 | # so, subject to the following conditions: 9 | # 10 | # The above copyright notice and this permission notice shall be included in all 11 | # copies or substantial portions of the Software. 12 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 13 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 14 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 15 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 16 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 17 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 18 | # SOFTWARE. 19 | 20 | # CHIP_IO Utilities 21 | # Random functions to enable fun stuff on the CHIP! 22 | 23 | # Credit goes to nonokuono (https://bbs.nextthing.co/users/nonokunono) 24 | # for gathering the i2cset commands from the AXP-209 datasheet for 2.0, 2.6, and 3.3V output 25 | # and for figuring out the ADC setup on the AXP-209 26 | 27 | import subprocess 28 | import glob 29 | import re 30 | 31 | # Global Variables 32 | DEBUG = False 33 | 34 | def toggle_debug(): 35 | global DEBUG 36 | if DEBUG: 37 | DEBUG = False 38 | print("debug disabled") 39 | else: 40 | DEBUG = True 41 | print("debug enabled") 42 | 43 | # Set the 1.8V-pin on the CHIP U13-header to given voltage 44 | # Return False on error 45 | def set_1v8_pin_voltage(voltage): 46 | if not is_chip_pro(): 47 | if not isinstance(voltage, int) and not isinstance(voltage, float): 48 | return False 49 | if voltage < 1.8 or voltage > 3.3: 50 | return False 51 | if DEBUG: 52 | print("Setting 1.8V Pin voltage: {0}".format(voltage)) 53 | voltage=int(round((voltage - 1.8) / 0.1)) << 4 54 | if subprocess.call(["/usr/sbin/i2cset", "-f", "-y" ,"0", "0x34", "0x90", "0x03"]): 55 | if DEBUG: 56 | print("Pin enable command failed") 57 | return False 58 | if subprocess.call(["/usr/sbin/i2cset", "-f", "-y", "0", "0x34", "0x91", str(voltage)]): 59 | if DEBUG: 60 | print("Pin set voltage command failed") 61 | return False 62 | return True 63 | else: 64 | print("Set 1.8V Pin Voltage not supported on the CHIP Pro") 65 | 66 | # Get the voltage the 1.8V-pin on the CHIP U13-header has been configured as 67 | # Return False on error 68 | def get_1v8_pin_voltage(): 69 | if not is_chip_pro(): 70 | p=subprocess.Popen(["/usr/sbin/i2cget", "-f", "-y", "0", "0x34", "0x90"], stdout=subprocess.PIPE) 71 | output=p.communicate()[0].decode("utf-8").strip() 72 | #Not configured as an output 73 | if output != "0x03": 74 | if DEBUG: 75 | print("1.8V Pin is currently disabled") 76 | return False 77 | p=subprocess.Popen(["/usr/sbin/i2cget", "-f", "-y", "0", "0x34", "0x91"], stdout=subprocess.PIPE) 78 | output=p.communicate()[0].decode("utf-8").strip() 79 | voltage=round((int(output, 16) >> 4) * 0.1 + 1.8, 1) 80 | if DEBUG: 81 | print("Current 1.8V Pin voltage: {0}".format(voltage)) 82 | return voltage 83 | else: 84 | print("Get 1.8V Pin Voltage not supported on the CHIP Pro") 85 | 86 | # Enable 1.8V Pin on CHIP U13 Header 87 | def enable_1v8_pin(): 88 | if not is_chip_pro(): 89 | set_1v8_pin_voltage(1.8) 90 | else: 91 | print("Enable 1.8V Pin not supported on the CHIP Pro") 92 | 93 | # Disable 1.8V Pin on CHIP U13 Header 94 | def disable_1v8_pin(): 95 | 96 | if not is_chip_pro(): 97 | if DEBUG: 98 | print("Disabling the 1.8V Pin") 99 | # CANNOT USE I2C LIB AS WE NEED TO FORCE THE COMMAND DUE TO THE KERNEL OWNING THE DEVICE 100 | # First we have to write 0x05 to AXP-209 Register 0x91 101 | subprocess.call('/usr/sbin/i2cset -f -y 0 0x34 0x91 0x05', shell=True) 102 | # Then we have to write 0x07 to AXP-209 Register 0x90 103 | subprocess.call('/usr/sbin/i2cset -f -y 0 0x34 0x90 0x07', shell=True) 104 | else: 105 | print("Disable 1.8V Pin not supported on the CHIP Pro") 106 | 107 | # Unexport All 108 | def unexport_all(): 109 | if DEBUG: 110 | print("Unexporting all the pins") 111 | gpios = glob.glob("/sys/class/gpio/gpio[0-9]*") 112 | for g in gpios: 113 | tmp = g.split("/") 114 | gpio = tmp[4] 115 | num = re.sub("[a-z]","",gpio) 116 | cmd = "echo " + num + " > /sys/class/gpio/unexport" 117 | subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE) 118 | 119 | # Determine Processor 120 | def is_chip_pro(): 121 | isgr8 = False 122 | if DEBUG: 123 | print("Determining if computer is CHIP or CHIP Pro") 124 | 125 | # GET FIRST LINE FROM /proc/meminfo 126 | f = open("/proc/meminfo","r") 127 | fline = f.readline() 128 | f.close() 129 | 130 | # FIGURE OUT OUR TOTAL MEMORY SIZE 131 | parts = fline.split() 132 | mem = float(parts[1]) / 1024 133 | 134 | if mem > 380: 135 | isgr8 = False 136 | if DEBUG: 137 | print("found CHIP!") 138 | else: 139 | isgr8 = True 140 | if DEBUG: 141 | print("found CHIP Pro!") 142 | 143 | # Return isgr8 144 | return isgr8 145 | -------------------------------------------------------------------------------- /test/test_pwm_setup.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import os 3 | import time 4 | 5 | import CHIP_IO.PWM as PWM 6 | import CHIP_IO.OverlayManager as OM 7 | import CHIP_IO.Utilities as UT 8 | 9 | def setup_module(module): 10 | if not UT.is_chip_pro(): 11 | OM.load("PWM0") 12 | 13 | def teardown_module(module): 14 | PWM.cleanup() 15 | if not UT.is_chip_pro(): 16 | OM.unload("PWM0") 17 | 18 | class TestPwmSetup: 19 | 20 | def setup_method(self, test_method): 21 | time.sleep(0.5) 22 | 23 | def test_start_pwm(self): 24 | PWM.start("PWM0", 0) 25 | 26 | pwm_test = '/sys/class/pwm/pwmchip0/pwm0/' 27 | 28 | assert os.path.exists(pwm_test) == True 29 | duty = open(pwm_test + 'duty_cycle').readline().strip() 30 | period = open(pwm_test + 'period').readline().strip() 31 | assert int(duty) == 0 32 | assert int(period) == 500000 33 | 34 | def test_start_pwm_with_polarity_one(self): 35 | PWM.cleanup() 36 | PWM.start("PWM0", 0, 2000, 1) 37 | 38 | pwm_test = '/sys/class/pwm/pwmchip0/pwm0/' 39 | 40 | duty = open(pwm_test + 'duty_cycle').readline().strip() 41 | period = open(pwm_test + 'period').readline().strip() 42 | polarity = open(pwm_test + 'polarity').readline().strip() 43 | assert int(duty) == 0 44 | assert int(period) == 500000 45 | assert str(polarity) == "inversed" 46 | 47 | def test_start_pwm_with_polarity_default(self): 48 | PWM.cleanup() 49 | PWM.start("PWM0", 0, 2000, 0) 50 | 51 | pwm_test = '/sys/class/pwm/pwmchip0/pwm0/' 52 | 53 | duty = open(pwm_test + 'duty_cycle').readline().strip() 54 | period = open(pwm_test + 'period').readline().strip() 55 | polarity = open(pwm_test + 'polarity').readline().strip() 56 | assert int(duty) == 0 57 | assert int(period) == 500000 58 | assert str(polarity) == "normal" 59 | 60 | def test_start_pwm_with_polarity_zero(self): 61 | PWM.cleanup() 62 | PWM.start("PWM0", 0, 2000, 0) 63 | 64 | pwm_test = '/sys/class/pwm/pwmchip0/pwm0/' 65 | 66 | duty = open(pwm_test + 'duty_cycle').readline().strip() 67 | period = open(pwm_test + 'period').readline().strip() 68 | polarity = open(pwm_test + 'polarity').readline().strip() 69 | assert int(duty) == 0 70 | assert int(period) == 500000 71 | assert str(polarity) == "normal" 72 | 73 | def test_pwm_start_invalid_pwm_key(self): 74 | with pytest.raises(ValueError): 75 | PWM.start("P8_25", -1) 76 | 77 | def test_pwm_start_invalid_duty_cycle_negative(self): 78 | with pytest.raises(ValueError): 79 | PWM.start("PWM0", -1) 80 | 81 | def test_pwm_start_valid_duty_cycle_min(self): 82 | #testing an exception isn't thrown 83 | PWM.cleanup() 84 | PWM.start("PWM0", 0) 85 | PWM.cleanup() 86 | 87 | def test_pwm_start_valid_duty_cycle_max(self): 88 | #testing an exception isn't thrown 89 | PWM.start("PWM0", 100) 90 | PWM.cleanup() 91 | 92 | def test_pwm_start_invalid_duty_cycle_high(self): 93 | with pytest.raises(ValueError): 94 | PWM.start("PWM0", 101) 95 | 96 | def test_pwm_start_invalid_duty_cycle_string(self): 97 | with pytest.raises(TypeError): 98 | PWM.start("PWM0", "1") 99 | 100 | def test_pwm_start_invalid_frequency_negative(self): 101 | with pytest.raises(ValueError): 102 | PWM.start("PWM0", 0, -1) 103 | 104 | def test_pwm_start_invalid_frequency_string(self): 105 | with pytest.raises(TypeError): 106 | PWM.start("PWM0", 0, "1") 107 | 108 | def test_pwm_start_negative_polarity(self): 109 | with pytest.raises(ValueError): 110 | PWM.start("PWM0", 0, 100, -1) 111 | 112 | def test_pwm_start_invalid_positive_polarity(self): 113 | with pytest.raises(ValueError): 114 | PWM.start("PWM0", 0, 100, 2) 115 | 116 | def test_pwm_start_invalid_polarity_type(self): 117 | with pytest.raises(TypeError): 118 | PWM.start("PWM0", 0, 100, "1") 119 | 120 | @pytest.mark.xfail(reason="pwm cleanup is doing weirdness for this test") 121 | def test_pwm_duty_modified(self): 122 | PWM.start("PWM0", 0) 123 | 124 | pwm_test = '/sys/class/pwm/pwmchip0/pwm0/' 125 | 126 | assert os.path.exists(pwm_test) == True 127 | duty = open(pwm_test + 'duty_cycle').readline().strip() 128 | period = open(pwm_test + 'period').readline().strip() 129 | assert int(duty) == 0 130 | assert int(period) == 500000 131 | 132 | PWM.set_duty_cycle("PWM0", 100) 133 | duty = open(pwm_test + 'duty_cycle').readline().strip() 134 | period = open(pwm_test + 'period').readline().strip() 135 | assert int(duty) == 500000 136 | assert int(period) == 500000 137 | 138 | def test_pwm_duty_cycle_non_setup_key(self): 139 | with pytest.raises(ValueError): 140 | PWM.cleanup() 141 | PWM.set_duty_cycle("PWM0", 100) 142 | 143 | def test_pwm_duty_cycle_invalid_key(self): 144 | with pytest.raises(ValueError): 145 | PWM.set_duty_cycle("P9_15", 100) 146 | 147 | def test_pwm_duty_cycle_invalid_value_high(self): 148 | PWM.start("PWM0", 0) 149 | with pytest.raises(ValueError): 150 | PWM.set_duty_cycle("PWM0", 101) 151 | PWM.cleanup() 152 | 153 | def test_pwm_duty_cycle_invalid_value_negative(self): 154 | PWM.start("PWM0", 0) 155 | with pytest.raises(ValueError): 156 | PWM.set_duty_cycle("PWM0", -1) 157 | PWM.cleanup() 158 | 159 | def test_pwm_duty_cycle_invalid_value_string(self): 160 | PWM.start("PWM0", 0) 161 | with pytest.raises(TypeError): 162 | PWM.set_duty_cycle("PWM0", "a") 163 | PWM.cleanup() 164 | 165 | def test_pwm_frequency_invalid_value_negative(self): 166 | PWM.start("PWM0", 0) 167 | with pytest.raises(ValueError): 168 | PWM.set_frequency("PWM0", -1) 169 | PWM.cleanup() 170 | 171 | def test_pwm_frequency_invalid_value_string(self): 172 | PWM.start("PWM0", 0) 173 | with pytest.raises(TypeError): 174 | PWM.set_frequency("PWM0", "11") 175 | PWM.cleanup() 176 | 177 | def test_pwm_freq_non_setup_key(self): 178 | with pytest.raises(RuntimeError): 179 | PWM.set_frequency("PWM0", 100) 180 | 181 | def test_pwm_freq_non_setup_key(self): 182 | with pytest.raises(ValueError): 183 | PWM.set_frequency("P9_15", 100) 184 | 185 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | ## CHIP_IO API Documentation 2 | 3 | * [CHIP_IO.GPIO](./gpio.md) 4 | * [CHIP_IO.PWM](./pwm.md) 5 | * [CHIP_IO.SOFTPWM](./softpwm.md) 6 | * [CHIP_IO.SERVO](./servo.md) 7 | * [CHIP_IO.LRADC](./lradc.md) 8 | * [CHIP_IO.Utilities](./utilities.md) 9 | * [CHIP_IO.OverlayManager](./overlaymanager.md) 10 | 11 | ### Allowable Pin Names and Edge Detection Capability 12 | 13 | The following "table" is the allowable pin names that are able to be used by the library. The Name column is the normal name used on the CHIP Headers, the Alt Name column is the value used by the PocketCHIP header (if it's broken out), and the Key is the Header and Pin Number the the Pin is physically located. Either of these 3 means is able to specify a pin in CHIP_IO. 14 | 15 | | CHIP (Main Name) | PocketCHIP/CHIP Pro Name | Key (Alt Name) | HW Support | Edge Detect | 16 | |:----------------:|:------------------------:|:--------------:|:---------------:|:---------------:| 17 | | TWI1-SDA | KPD-I2C-SDA | U13_9 | CHIP/CHIP PRO | NO | 18 | | TWI1-SCK | KPD-I2C-SCL | U13_11 | CHIP/CHIP PRO | NO | 19 | | LCD-D2 | UART2-TX | U13_17 | CHIP/CHIP PRO | NO | 20 | | PWM0 | PWM0 | U13_18 | CHIP/CHIP PRO | NO | 21 | | PWM1 | PWM1 | EINT13 | CHIP PRO | YES | 22 | | LCD-D4 | UART2-CTS | U13_19 | CHIP/CHIP PRO | NO | 23 | | LCD-D3 | UART2-RX | U13_20 | CHIP/CHIP PRO | NO | 24 | | LCD-D6 | LCD-D6 | U13_21 | CHIP | NO | 25 | | LCD-D5 | UART2-RTS | U13_22 | CHIP/CHIP PRO | NO | 26 | | LCD-D10 | LCD-D10 | U13_23 | CHIP | NO | 27 | | LCD-D7 | LCD-D7 | U13_24 | CHIP | NO | 28 | | LCD-D12 | LCD-D12 | U13_25 | CHIP | NO | 29 | | LCD-D11 | LCD-D11 | U13_26 | CHIP | NO | 30 | | LCD-D14 | LCD-D14 | U13_27 | CHIP | NO | 31 | | LCD-D13 | LCD-D13 | U13_28 | CHIP | NO | 32 | | LCD-D18 | LCD-D18 | U13_29 | CHIP | NO | 33 | | LCD-D15 | LCD-D15 | U13_30 | CHIP | NO | 34 | | LCD-D20 | LCD-D20 | U13_31 | CHIP | NO | 35 | | LCD-D19 | LCD-D19 | U13_32 | CHIP | NO | 36 | | LCD-D22 | LCD-D22 | U13_33 | CHIP | NO | 37 | | LCD-D21 | LCD-D21 | U13_34 | CHIP | NO | 38 | | LCD-CLK | LCD-CLK | U13_35 | CHIP | NO | 39 | | LCD-D23 | LCD-D23 | U13_36 | CHIP | NO | 40 | | LCD-VSYNC | LCD-VSYNC | U13_37 | CHIP | NO | 41 | | LCD-HSYNC | LCD-HSYNC | U13_38 | CHIP | NO | 42 | | LCD-DE | LCD-DE | U13_40 | CHIP | NO | 43 | | UART1-TX | UART-TX | U14_3 | CHIP/CHIP PRO | NO | 44 | | UART1-RX | UART-RX | U14_5 | CHIP/CHIP PRO | NO | 45 | | LRADC | ADC | U14_11 | CHIP/CHIP PRO | NO | 46 | | XIO-P0 | XIO-P0 | U14_13 | CHIP | YES | 47 | | XIO-P1 | XIO-P1 | U14_14 | CHIP | YES | 48 | | XIO-P2 | GPIO1 | U14_15 | CHIP | YES | 49 | | XIO-P3 | GPIO2 | U14_16 | CHIP | YES | 50 | | XIO-P4 | GPIO3 | U14_17 | CHIP | YES | 51 | | XIO-P5 | GPIO4 | U14_18 | CHIP | YES | 52 | | XIO-P6 | GPIO5 | U14_19 | CHIP | YES | 53 | | XIO-P7 | GPIO6 | U14_20 | CHIP | YES | 54 | | AP-EINT1 | KPD-INT | U14_23 | CHIP/CHIP PRO | YES | 55 | | AP-EINT3 | AP-INT3 | U14_24 | CHIP/CHIP PRO | YES | 56 | | TWI2-SDA | I2C-SDA | U14_25 | CHIP/CHIP PRO | NO | 57 | | TWI2-SCK | I2C-SCL | U14_26 | CHIP/CHIP PRO | NO | 58 | | CSIPCK | SPI-SEL | U14_27 | CHIP/CHIP PRO | NO | 59 | | CSICK | SPI-CLK | U14_28 | CHIP/CHIP PRO | NO | 60 | | CSIHSYNC | SPI-MOSI | U14_29 | CHIP/CHIP PRO | NO | 61 | | CSIVSYNC | SPI-MISO | U14_30 | CHIP/CHIP PRO | NO | 62 | | CSID0 | D0 | U14_31 | CHIP/CHIP PRO | NO | 63 | | CSID1 | D1 | U14_32 | CHIP/CHIP PRO | NO | 64 | | CSID2 | D2 | U14_33 | CHIP/CHIP PRO | NO | 65 | | CSID3 | D3 | U14_34 | CHIP/CHIP PRO | NO | 66 | | CSID4 | D4 | U14_35 | CHIP/CHIP PRO | NO | 67 | | CSID5 | D5 | U14_36 | CHIP/CHIP PRO | NO | 68 | | CSID6 | D6 | U14_37 | CHIP/CHIP PRO | NO | 69 | | CSID7 | D7 | U14_38 | CHIP/CHIP PRO | NO | 70 | | I2S-MCLK | EINT19 | 21 | CHIP PRO | YES | 71 | | I2S-BCLK | I2S-BCLK | 22 | CHIP PRO | NO | 72 | | I2S-LCLK | I2S-LCLK | 23 | CHIP PRO | NO | 73 | | I2S-DO | EINT19 | 24 | CHIP PRO | NO | 74 | | I2S-DI | EINT24 | 25 | CHIP PRO | YES | 75 | 76 | -------------------------------------------------------------------------------- /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | 0.7.1 2 | --- 3 | * Merged in PR #79 4 | * Merged in PR #80 5 | * Added message notifying user of the gpio set direction retry 6 | 7 | 0.7.0 8 | --- 9 | * Added ability to specify GPIO only as a number, this doesn't work for PWM/SPWM/LRADC/SERVO 10 | 11 | 0.6.2 12 | --- 13 | * Implementation for #77 - ability to push up binary pypi 14 | * Implementation for #75 - wait_for_edge timeout 15 | 16 | 0.6.1 17 | --- 18 | * Fixing implementation for #76 19 | 20 | 0.6 21 | --- 22 | * Random comment cleanup 23 | * Implement fix for #76 24 | * API documentation added 25 | * Closing #74 26 | 27 | 0.5.9 28 | --- 29 | * Merged PR#70 to enable the underlying C code to be used properly in C based code 30 | * Updated README to add missing pins on the CHIP Pro that are available as GPIO 31 | * Updated README to denote pins that are available for Edge Detection 32 | 33 | 0.5.8 34 | --- 35 | * Added 3 pins for the CHIP Pro as allowable for setting callbacks and edge detection to close out Issue #68 36 | 37 | 0.5.7 38 | --- 39 | * Added the I2S pins on the CHIP Pro as GPIO capable 40 | * Added per PWM/SoftPWM cleanup per Issue #64 41 | 42 | 0.5.6 43 | --- 44 | * Fix for Issue #63 where re-setting up a pin wasn't lining up with RPi.GPIO standards. Calling setup after the first time will now update direction. 45 | * README updates to point out the direction() function since that was missing 46 | 47 | 0.5.5 48 | --- 49 | * Fix for Issue #62 where using alternate name of an XIO would cause a segfault due to trying to set pull up/down resistor setting 50 | 51 | 0.5.4 52 | --- 53 | * Re-enabled the polarity setting for PWM based upon Issue #61 54 | * Fixed a 1 letter bug was trying to write inverted to polarity when it wants inversed (such facepalm) 55 | * Cleaned up the polarity setting code to work when PWM is not enabled 56 | * Fixed the unit test for pwm to verify we can set polarity 57 | 58 | 0.5.3 59 | --- 60 | * Fixes to the PWM pytest 61 | * Added pytest for LRADC and Utilities 62 | * Makefile updates for all the things 63 | 64 | 0.5.2 65 | --- 66 | * Updating Utilties to determine CHIP Pro better 67 | * Updating the README to fix things 68 | 69 | 0.5.0 70 | --- 71 | * CHIP Pro Support 72 | * README Updates 73 | 74 | 0.4.0 75 | --- 76 | * Software Servo code added 77 | - Only works on the LCD and CSI pins 78 | * Fixed cleanup() for the SOFTPWM and SERVO 79 | - The per pin cleanup for SOFTPWM doesn't work as stop() clears up the memory for the pin used 80 | - SERVO code was based on SOFTPWM, so it inherited this issue 81 | 82 | 0.3.5 83 | --- 84 | * Merged in brettcvz's code to read a byte of data from the GPIO 85 | - Cleaned the code up and expanded it (in the low level C code) to read up to 32 bits of data 86 | - Presented 8 bit and 16 bits of data functions to the Python interface with brettcvz's read_byte() and my read_word() 87 | * I think I finally fixed the GPIO.cleanup() code one and for all 88 | 89 | 0.3.4.1 90 | --- 91 | * Quick fix as I borked XIO setup as inputs with the latest change that enabled PUD 92 | 93 | 0.3.4 94 | --- 95 | * Pull Up/Pull Down resistor setting now available for the R8 GPIO. 96 | * Some general cleanup 97 | 98 | 0.3.3 99 | ---- 100 | * Added Debug printing for all the capabilities with the toggle_debug() function 101 | * Added 2 functions from @streamnsight for PWM that allow for setting the period of the PWM and the Pulse Width, both in nanoseconds 102 | * Fixed the SPI2 overlay stuff by using the NTC overlay instead of mine. 103 | 104 | 0.3.2 105 | ---- 106 | * Fixing issue #53 to handle the return values of the set functions in pwm_enable. 107 | * Start of whole library debug for #55 108 | 109 | 0.3.1 110 | ---- 111 | * Fixing issue #50 where I broke GPIO.cleanup() and SOFTPWM.cleanup() when no input is specified. 112 | 113 | 0.3.0 114 | ---- 115 | * Added setmode() function for GPIO to maintain compatibility with Raspberry Pi scripts, this function literally does nothing 116 | * Added per pin cleanup functionality for GPIO and SoftPWM so you can unexport a pin without unexporting every pin 117 | * Updated README to make edge detection wording a little better and to add the per pin cleanup code 118 | * Version update since I blasted through 3 issues on github and feel like we need a nice bump to 0.3 119 | 120 | 0.2.7 121 | ---- 122 | * Fix to the Enable 1.8V Pin code as it wasn't working due to bit shifting isn't allowed on a float. 123 | * Updated README to denote the PocketCHIP Pin names better 124 | 125 | 0.2.6 126 | ---- 127 | * Fix to keep the GPIO value file open until the pin is unexported (issue #34) 128 | 129 | 0.2.5 130 | ---- 131 | * Updates to the pytest code for HWPWM and SoftPWM 132 | * Removed the i2c-1 load/unload support in OverlayManager as CHIP Kernel 4.4.13 has that bus brought back by default 133 | 134 | 0.2.4 135 | ---- 136 | * HW PWM Fixed 137 | - Start/Stop/Duty Cycle/Frequency settings work 138 | - Polarity cannot be changed, so don't bother setting it to 1 in start() 139 | * Added the unexport_all() function to Utilites 140 | 141 | 0.2.3 142 | ---- 143 | * LRADC Support 144 | * Added Utilities 145 | - Enable/Disable the 1.8V Pin 146 | - Change 1.8V Pin to output either 2.0V, 2.6V, or 3.3V 147 | (Current limited to 50mA) 148 | 149 | 0.2.2 150 | ---- 151 | * Fixes for Issue #16 152 | - Pass SoftPWM setup errors to Python layer (aninternetof) 153 | - Updated spwmtest.py to test for this issue 154 | 155 | 0.2.1 156 | ---- 157 | * Pull request #12 fixes: 158 | - Fixed indent in the i2c-1 dts 159 | - Removed import dependencies in the SPI and PWM overlays 160 | - Re-enabled building of the dtbo on setup.py install 161 | 162 | 0.2.0 163 | ---- 164 | * Added the ability to load DTB Overlays from within CHIP_IO 165 | - Support for PWM0, SPI2, and I2C-1 (which comes back as i2c-3 on the 4.4 CHIP 166 | - Support for a custom DTB Overlay 167 | * Fixes to the pwm unit test, all but 2 now pass :) 168 | 169 | 0.1.2 170 | ---- 171 | * SoftPWM Fix by aninternetof 172 | * Added a verification test for SoftPWM 173 | 174 | 0.1.1 175 | ---- 176 | * Some refactoring of the edge detection code, made it function better 177 | * Added Rising and Both edge detection tests to gptest.py 178 | - Small issue with both edge triggering double pumping on first callback hit 179 | 180 | 0.1.0 181 | ---- 182 | * Fixed edge detection code, will trigger proper for callbacks now 183 | 184 | 0.0.9 185 | ---- 186 | * Fixed SoftPWM segfault 187 | * Added Alternate Names for the GPIOs 188 | 189 | 0.0.8 190 | ---- 191 | * Updates to handle the 4.4 kernel CHIPs. Numerous fixes to fix code issues. 192 | * Added ability to get the XIO base into Python. 193 | * Still need a proper overlay for Hardware PWM and SPI. 194 | 195 | 0.0.7 196 | ---- 197 | * GPIO edge detection expanded to include AP-EINT1 and AP-EINT3 as those are the only other pins that support edge detection 198 | 199 | 0.0.6 200 | ---- 201 | * Initial PWM 202 | * GPIO edge detection and callback for XIO-P0 to XIO-P7 working 203 | 204 | 0.0.4 205 | ____ 206 | * Initial Commit 207 | * GPIO working - untested callback and edge detection 208 | * Initial GPIO unit tests 209 | 210 | 211 | -------------------------------------------------------------------------------- /CHIP_IO/LRADC.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2016 Robert Wolterman 2 | # 3 | # Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | # this software and associated documentation files (the "Software"), to deal in 5 | # the Software without restriction, including without limitation the rights to 6 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 7 | # of the Software, and to permit persons to whom the Software is furnished to do 8 | # so, subject to the following conditions: 9 | # 10 | # The above copyright notice and this permission notice shall be included in all 11 | # copies or substantial portions of the Software. 12 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 13 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 14 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 15 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 16 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 17 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 18 | # SOFTWARE. 19 | 20 | import os 21 | import time 22 | 23 | # Global Variables 24 | DEBUG = False 25 | DEVICE_EXIST = True 26 | 27 | # Default Sample Rate Variables 28 | SAMPLE_RATE_32P25 = 32.25 29 | SAMPLE_RATE_62O5 = 62.5 30 | SAMPLE_RATE_125 = 125 31 | SAMPLE_RATE_250 = 250 32 | SAMPLE_RATES = [] 33 | 34 | # Scale Factor 35 | SCALE_FACTOR = 31.25 36 | 37 | # File Locations 38 | LRADC_BASE_DEVICE_FILE = "/sys/bus/iio/devices/iio:device0" 39 | AVAILABLE_SAMPLE_RATE_FILE = "/sampling_frequency_available" 40 | SCALE_FACTOR_FILE = "/in_voltage_scale" 41 | CURRENT_SAMPLE_RATE_FILE = "/in_voltage_sampling_frequency" 42 | RAW_VOLTAGE_CHAN0_FILE = "/in_voltage0_raw" 43 | RAW_VOLTAGE_CHAN1_FILE = "/in_voltage1_raw" 44 | 45 | def toggle_debug(): 46 | global DEBUG 47 | if DEBUG: 48 | DEBUG = False 49 | print("debug disabled") 50 | else: 51 | DEBUG = True 52 | print("debug enabled") 53 | 54 | def setup(rate=250): 55 | # First we determine if the device exists 56 | if not os.path.exists(LRADC_BASE_DEVICE_FILE): 57 | global DEVICE_EXIST 58 | DEVICE_EXIST = False 59 | raise Exception("LRADC Device does not exist") 60 | else: 61 | # Set the Sample Rate 62 | set_sample_rate(rate) 63 | 64 | def get_device_exist(): 65 | return DEVICE_EXIST 66 | 67 | def get_scale_factor(): 68 | # If we do not have a device, lets throw an exception 69 | if not DEVICE_EXIST: 70 | raise Exception("LRADC Device does not exist") 71 | 72 | # Get the data from the file 73 | f = open(LRADC_BASE_DEVICE_FILE+SCALE_FACTOR_FILE,"r") 74 | dat = f.readline() 75 | f.close() 76 | 77 | # Set the Scale Factor 78 | global SCALE_FACTOR 79 | SCALE_FACTOR = float(dat.strip()) 80 | 81 | # Debug 82 | if DEBUG: 83 | print("lradc.get_scale_factor: {0}".format(SCALE_FACTOR)) 84 | 85 | return SCALE_FACTOR 86 | 87 | def get_allowable_sample_rates(): 88 | # If we do not have a device, lets throw an exception 89 | if not DEVICE_EXIST: 90 | raise Exception("LRADC Device does not exist") 91 | 92 | # Get the data from the file 93 | f = open(LRADC_BASE_DEVICE_FILE+AVAILABLE_SAMPLE_RATE_FILE,"r") 94 | dat = f.readline() 95 | f.close() 96 | 97 | global SAMPLE_RATES 98 | tmp = dat.strip().split(" ") 99 | for i in range(len(tmp)): 100 | if "." in tmp[i]: 101 | tmp[i] = float(tmp[i]) 102 | else: 103 | tmp[i] = int(tmp[i]) 104 | SAMPLE_RATES = tmp 105 | 106 | # Debug 107 | if DEBUG: 108 | print("lradc.get_allowable_sample_rates:") 109 | for rate in SAMPLE_RATES: 110 | print("{0}".format(rate)) 111 | 112 | return tuple(SAMPLE_RATES) 113 | 114 | def set_sample_rate(rate): 115 | # If we do not have a device, lets throw an exception 116 | if not DEVICE_EXIST: 117 | raise Exception("LRADC Device does not exist") 118 | 119 | # Check to see if the rates were gathered already 120 | global SAMPLE_RATES 121 | if SAMPLE_RATES == []: 122 | tmp = get_allowable_sample_rates() 123 | 124 | # Range check the input rate 125 | if rate not in SAMPLE_RATES: 126 | raise ValueError("Input Rate an Acceptable Value") 127 | 128 | # Debug 129 | if DEBUG: 130 | print("lradc.set_sample_rate: {0}".format(rate)) 131 | 132 | # Write the rate 133 | f = open(LRADC_BASE_DEVICE_FILE+CURRENT_SAMPLE_RATE_FILE,"w") 134 | mystr = "%.2f" % rate 135 | f.write(mystr) 136 | f.close() 137 | 138 | # Verify write went well 139 | crate = get_sample_rate() 140 | if crate != rate: 141 | raise Exception("Unable to write new Sampling Rate") 142 | 143 | def get_sample_rate(): 144 | # If we do not have a device, lets throw an exception 145 | if not DEVICE_EXIST: 146 | raise Exception("LRADC Device does not exist") 147 | 148 | # Get the data from the file 149 | f = open(LRADC_BASE_DEVICE_FILE+CURRENT_SAMPLE_RATE_FILE,"r") 150 | dat = f.read() 151 | f.close() 152 | 153 | dat = dat.strip() 154 | if "." in dat: 155 | dat = float(dat) 156 | else: 157 | dat = int(dat) 158 | 159 | # Debug 160 | if DEBUG: 161 | print("lradc.get_sample_rate: {0}".format(dat)) 162 | 163 | return dat 164 | 165 | def get_chan0_raw(): 166 | # If we do not have a device, lets throw an exception 167 | if not DEVICE_EXIST: 168 | raise Exception("LRADC Device does not exist") 169 | 170 | # Get the data from the file 171 | f = open(LRADC_BASE_DEVICE_FILE+RAW_VOLTAGE_CHAN0_FILE,"r") 172 | dat = f.readline() 173 | f.close() 174 | 175 | dat = float(dat.strip()) 176 | 177 | # Debug 178 | if DEBUG: 179 | print("lradc.get_chan0_raw: {0}".format(dat)) 180 | 181 | return dat 182 | 183 | def get_chan1_raw(): 184 | # If we do not have a device, lets throw an exception 185 | if not DEVICE_EXIST: 186 | raise Exception("LRADC Device does not exist") 187 | 188 | # Get the data from the file 189 | f = open(LRADC_BASE_DEVICE_FILE+RAW_VOLTAGE_CHAN1_FILE,"r") 190 | dat = f.readline() 191 | f.close() 192 | 193 | dat = float(dat.strip()) 194 | 195 | # Debug 196 | if DEBUG: 197 | print("lradc.get_chan1_raw: {0}".format(dat)) 198 | 199 | return dat 200 | 201 | def get_chan0(): 202 | # If we do not have a device, lets throw an exception 203 | if not DEVICE_EXIST: 204 | raise Exception("LRADC Device does not exist") 205 | 206 | # Get the raw data first 207 | dat = get_chan0_raw() 208 | # Apply scale factor 209 | dat *= SCALE_FACTOR 210 | 211 | # Debug 212 | if DEBUG: 213 | print("lradc.get_chan0: {0}".format(dat)) 214 | 215 | return dat 216 | 217 | def get_chan1(): 218 | # If we do not have a device, lets throw an exception 219 | if not DEVICE_EXIST: 220 | raise Exception("LRADC Device does not exist") 221 | 222 | # Get the raw data first 223 | dat = get_chan1_raw() 224 | # Apply scale factor 225 | dat *= SCALE_FACTOR 226 | 227 | # Debug 228 | if DEBUG: 229 | print("lradc.get_chan1: {0}".format(dat)) 230 | 231 | return dat 232 | 233 | 234 | -------------------------------------------------------------------------------- /CHIP_IO/OverlayManager.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2016 Robert Wolterman 2 | # 3 | # Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | # this software and associated documentation files (the "Software"), to deal in 5 | # the Software without restriction, including without limitation the rights to 6 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 7 | # of the Software, and to permit persons to whom the Software is furnished to do 8 | # so, subject to the following conditions: 9 | # 10 | # The above copyright notice and this permission notice shall be included in all 11 | # copies or substantial portions of the Software. 12 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 13 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 14 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 15 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 16 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 17 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 18 | # SOFTWARE. 19 | 20 | import os 21 | import shutil 22 | import time 23 | import sys 24 | from .Utilities import is_chip_pro 25 | 26 | DEBUG = False 27 | 28 | OVERLAYINSTALLPATH = "/lib/firmware/nextthingco/chip" 29 | OVERLAYCONFIGPATH = "/sys/kernel/config/device-tree/overlays" 30 | CUSTOMOVERLAYFILEPATH = "" 31 | 32 | PWMSYSFSPATH = "/sys/class/pwm/pwmchip0" 33 | # USING THE BASE DIRECTORY FOR SPI AS THE DEVICE NUMBER CHANGES ON LOAD/UNLOAD 34 | SPI2SYSFSPATH = "/sys/class/spi_master/" 35 | 36 | # LOADED VARIABLES 37 | # DO NOT MODIFY BY HAND WHEN USING 38 | # AS IT COULD BREAK FUNCTIONALITY 39 | _LOADED = { 40 | "SPI2" : False, 41 | "PWM0" : False, 42 | "CUST" : False 43 | } 44 | 45 | _OVERLAYS = { 46 | "SPI2" : "sample-spi.dtbo", 47 | "PWM0" : "sample-pwm.dtbo", 48 | "CUST" : "" 49 | } 50 | 51 | _FOLDERS = { 52 | "SPI2" : "chip-spi", 53 | "PWM0" : "chip-pwm", 54 | "CUST" : "chip-cust" 55 | } 56 | 57 | def toggle_debug(): 58 | global DEBUG 59 | if DEBUG: 60 | DEBUG = False 61 | print("debug disabled") 62 | else: 63 | DEBUG = True 64 | print("debug enabled") 65 | 66 | def get_spi_loaded(): 67 | """ 68 | get_spi_loaded - Returns True/False based upon if the spi2 Overlay is loaded 69 | """ 70 | global _LOADED 71 | return _LOADED["SPI2"] 72 | 73 | def get_pwm_loaded(): 74 | """ 75 | get_pwm_loaded - Returns True/False based upon if the pwm0 Overlay is loaded 76 | """ 77 | global _LOADED 78 | return _LOADED["PWM0"] 79 | 80 | def get_custom_loaded(): 81 | """ 82 | get_custom_loaded - Returns True/False based upon if a Custom Overlay is loaded 83 | """ 84 | global _LOADED 85 | return _LOADED["CUST"] 86 | 87 | def _set_overlay_verify(name, overlay_path, config_path): 88 | """ 89 | _set_overlay_verify - Function to load the overlay and verify it was setup properly 90 | """ 91 | global DEBUG 92 | # VERIFY PATH IS NOT THERE 93 | if os.path.exists(config_path): 94 | print("Config path already exists! Not moving forward") 95 | print("config_path: {0}".format(config_path)) 96 | return -1 97 | 98 | # MAKE THE CONFIGURATION PATH 99 | os.makedirs(config_path) 100 | 101 | # CAT THE OVERLAY INTO THE CONFIG FILESYSTEM 102 | with open(config_path + "/dtbo", 'wb') as outfile: 103 | with open(overlay_path, 'rb') as infile: 104 | shutil.copyfileobj(infile, outfile) 105 | 106 | # SLEEP TO ENABLE THE KERNEL TO DO ITS JOB 107 | time.sleep(0.2) 108 | 109 | # VERIFY 110 | if name == "CUST": 111 | # BLINDLY ACCEPT THAT IT LOADED 112 | return 0 113 | elif name == "PWM0": 114 | if os.path.exists(PWMSYSFSPATH): 115 | if DEBUG: 116 | print("PWM IS LOADED!") 117 | return 0 118 | else: 119 | if DEBUG: 120 | print("ERROR LOAIDNG PWM0") 121 | return 1 122 | elif name == "SPI2": 123 | if os.listdir(SPI2SYSFSPATH) != "": 124 | if DEBUG: 125 | print("SPI2 IS LOADED!") 126 | return 0 127 | else: 128 | if DEBUG: 129 | print("ERROR LOADING SPI2") 130 | return 0 131 | 132 | def load(overlay, path=""): 133 | """ 134 | load - Load a DTB Overlay 135 | 136 | Inputs: 137 | overlay - Overlay Key: SPI2, PWM0, CUST 138 | path - Full Path to where the custom overlay is stored 139 | 140 | Returns: 141 | 0 - Successful Load 142 | 1 - Unsuccessful Load 143 | 2 - Overlay was previously set 144 | """ 145 | global DEBUG 146 | global _LOADED 147 | if DEBUG: 148 | print("LOAD OVERLAY: {0} @ {1}".format(overlay,path)) 149 | # SEE IF OUR OVERLAY NAME IS IN THE KEYS 150 | if overlay.upper() in _OVERLAYS.keys(): 151 | cpath = OVERLAYCONFIGPATH + "/" + _FOLDERS[overlay.upper()] 152 | if DEBUG: 153 | print("VALID OVERLAY") 154 | print("CONFIG PATH: {0}".format(cpath)) 155 | # CHECK TO SEE IF WE HAVE A PATH FOR CUSTOM OVERLAY 156 | if overlay.upper() == "CUST" and path == "": 157 | raise ValueError("Path must be specified for Custom Overlay Choice") 158 | elif overlay.upper() == "CUST" and _LOADED[overlay.upper()]: 159 | print("Custom Overlay already loaded") 160 | return 2 161 | elif overlay.upper() == "CUST" and not os.path.exists(path): 162 | print("Custom Overlay path does not exist") 163 | return 1 164 | 165 | # DETERMINE IF WE ARE A CHIP PRO AND WE ARE COMMANDED TO LOAD PWM0 166 | if is_chip_pro() and overlay.upper() == "PWM0": 167 | print("CHIP Pro supports PWM0 in base DTB, exiting") 168 | return 1 169 | 170 | # SET UP THE OVERLAY PATH FOR OUR USE 171 | if overlay.upper() != "CUST": 172 | opath = OVERLAYINSTALLPATH 173 | opath += "/" + _OVERLAYS[overlay.upper()] 174 | else: 175 | opath = path 176 | if DEBUG: 177 | print("OVERLAY PATH: {0}".format(opath)) 178 | 179 | if overlay.upper() == "PWM0" and _LOADED[overlay.upper()]: 180 | print("PWM0 Overlay already loaded") 181 | return 2 182 | 183 | if overlay.upper() == "SPI2" and _LOADED[overlay.upper()]: 184 | print("SPI2 Overlay already loaded") 185 | return 2 186 | 187 | # LOAD THE OVERLAY 188 | errc = _set_overlay_verify(overlay.upper(), opath, cpath) 189 | if DEBUG: 190 | print("_SET_OVERLAY_VERIFY ERRC: {0}".format(errc)) 191 | if errc == 0: 192 | _LOADED[overlay.upper()] = True 193 | 194 | else: 195 | raise ValueError("Invalid Overlay name specified! Choose between: SPI2, PWM0, CUST") 196 | 197 | def unload(overlay): 198 | global DEBUG 199 | global _LOADED 200 | if DEBUG: 201 | print("UNLOAD OVERLAY: {0}".format(overlay)) 202 | 203 | # DETERMINE IF WE ARE A CHIP PRO AND WE ARE COMMANDED TO UNLOAD PWM0 204 | if is_chip_pro() and overlay.upper() == "PWM0": 205 | print("CHIP Pro supports PWM0 in base DTB, exiting") 206 | return 207 | 208 | # SEE IF OUR OVERLAY NAME IS IN THE KEYS 209 | if overlay.upper() in _OVERLAYS.keys(): 210 | # BRUTE FORCE REMOVE AS THE DIRECTORY CONTAINS FILES 211 | os.system('rmdir \"{}\"'.format(OVERLAYCONFIGPATH + "/" + _FOLDERS[overlay.upper()])) 212 | _LOADED[overlay.upper()] = False 213 | else: 214 | raise ValueError("Invalid Overlay name specified! Choose between: SPI2, PWM0, CUST") 215 | 216 | 217 | -------------------------------------------------------------------------------- /test/integrations/gptest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import CHIP_IO.GPIO as GPIO 4 | import time 5 | import threading 6 | 7 | num_callbacks = 0 8 | 9 | def myfuncallback(channel): 10 | global num_callbacks 11 | num_callbacks += 1 12 | print("CALLBACK LIKE DRAKE IN HOTLINE BLING") 13 | 14 | 15 | loopfunction_exit = False 16 | 17 | def loopfunction(): 18 | print("LOOP FUNCTION START") 19 | for i in xrange(4): 20 | if loopfunction_exit: 21 | break 22 | if i % 2: 23 | mystr = "SETTING CSID0 LOW (i=%d)" % i 24 | print(mystr) 25 | GPIO.output("CSID0", GPIO.LOW) 26 | else: 27 | mystr = "SETTING CSID0 HIGH (i=%d)" % i 28 | print(mystr) 29 | GPIO.output("CSID0", GPIO.HIGH) 30 | print(" LOOP FUNCTION SLEEPING") 31 | time.sleep(1) 32 | 33 | num_errs = 0 34 | 35 | print("GETTING CHIP_IO VERSION") 36 | mystr = "CHIP_IO VERSION: %s" % GPIO.VERSION 37 | print(mystr) 38 | 39 | print("\nRUNNING GPIO SELF TEST") 40 | GPIO.selftest(0) 41 | 42 | print("\nVERIFYING SIMPLE FUNCTIONALITY") 43 | GPIO.setup("GPIO1", GPIO.IN) 44 | GPIO.setup("CSID0", GPIO.OUT, initial=GPIO.HIGH) 45 | if (GPIO.input("GPIO1") != GPIO.HIGH): 46 | print(" A high output on CSI0 does not lead to a high input on XIO-P2.") 47 | print(" Perhaps you forgot to connect them?") 48 | num_errs += 1 49 | else: 50 | print(" Able to use alternate names for GPIO") 51 | GPIO.cleanup() 52 | 53 | GPIO.setup("U14_15", GPIO.IN) # XIO-P2 54 | GPIO.setup("CSID0", GPIO.OUT, initial=GPIO.LOW) 55 | if (GPIO.input("XIO-P2") != GPIO.LOW): 56 | print(" A low output on CSI0 does not lead to a low input on XIO-P2.") 57 | print(" Perhaps you forgot to connect them?") 58 | num_errs += 1 59 | else: 60 | print(" Able to use Pin Header+Number for GPIO") 61 | GPIO.cleanup() 62 | 63 | GPIO.setup("XIO-P2", GPIO.IN) 64 | GPIO.setup("U14_31", GPIO.OUT) # CSID0 65 | 66 | print("READING XIO-P2") 67 | GPIO.output("CSID0", GPIO.HIGH) 68 | assert(GPIO.input("XIO-P2") == GPIO.HIGH) 69 | 70 | GPIO.output("CSID0", GPIO.LOW) 71 | print "LOW", GPIO.input("GPIO1") 72 | assert(GPIO.input("GPIO1") == GPIO.LOW) 73 | 74 | # ============================================== 75 | # EDGE DETECTION - AP-EINT1 76 | print("\nSETTING UP RISING EDGE DETECTION ON AP-EINT1") 77 | GPIO.setup("AP-EINT1", GPIO.IN) 78 | GPIO.add_event_detect("AP-EINT1", GPIO.RISING, myfuncallback) 79 | print("VERIFYING EDGE DETECT WAS SET PROPERLY") 80 | f = open("/sys/class/gpio/gpio193/edge", "r") 81 | edge = f.read() 82 | f.close() 83 | assert(edge == "rising\n") 84 | GPIO.remove_event_detect("AP-EINT1") 85 | 86 | # ============================================== 87 | # EDGE DETECTION - AP-EINT3 88 | print("\nSETTING UP BOTH EDGE DETECTION ON AP-EINT3") 89 | GPIO.setup("AP-EINT3", GPIO.IN) 90 | GPIO.add_event_detect("AP-EINT3", GPIO.BOTH, myfuncallback) 91 | print("VERIFYING EDGE DETECT WAS SET PROPERLY") 92 | f = open("/sys/class/gpio/gpio35/edge", "r") 93 | edge = f.read() 94 | f.close() 95 | assert(edge == "both\n") 96 | GPIO.remove_event_detect("AP-EINT3") 97 | 98 | # ============================================== 99 | # EDGE DETECTION - EXPANDED GPIO 100 | print("\nSETTING UP FALLING EDGE DETECTION ON XIO-P2") 101 | # WRITING CSID0 LOW FIRST AS THERE IS A DOUBLE HIT ON HIGH 102 | GPIO.output("CSID0", GPIO.LOW) 103 | GPIO.add_event_detect("XIO-P2", GPIO.FALLING, myfuncallback) 104 | 105 | print("VERIFYING EDGE DETECT") 106 | base = GPIO.get_gpio_base() 107 | gfile = "/sys/class/gpio/gpio%d/edge" % (base + 2) 108 | f = open(gfile, "r") 109 | edge = f.read() 110 | f.close() 111 | assert(edge == "falling\n") 112 | 113 | # LOOP WRITING ON CSID0 TO HOPEFULLY GET CALLBACK TO WORK 114 | print("WAITING FOR CALLBACKS ON XIO-P2") 115 | loopfunction() 116 | mystr = " num_callbacks = %d" % num_callbacks 117 | print(mystr) 118 | GPIO.remove_event_detect("XIO-P2") 119 | 120 | print("\nSETTING UP RISING EDGE DETECTION ON XIO-P2") 121 | # WRITING CSID0 LOW FIRST AS THERE IS A DOUBLE HIT ON HIGH 122 | GPIO.output("CSID0", GPIO.LOW) 123 | num_callbacks = 0 124 | GPIO.add_event_detect("XIO-P2", GPIO.RISING, myfuncallback) 125 | print("WAITING FOR CALLBACKS ON XIO-P2") 126 | loopfunction() 127 | mystr = " num_callbacks = %d" % num_callbacks 128 | print(mystr) 129 | GPIO.remove_event_detect("XIO-P2") 130 | 131 | print("\nSETTING UP BOTH EDGE DETECTION ON XIO-P2") 132 | # WRITING CSID0 LOW FIRST AS THERE IS A DOUBLE HIT ON HIGH 133 | GPIO.output("CSID0", GPIO.LOW) 134 | num_callbacks = 0 135 | GPIO.add_event_detect("XIO-P2", GPIO.BOTH, myfuncallback) 136 | print("WAITING FOR CALLBACKS ON XIO-P2") 137 | loopfunction() 138 | mystr = " num_callbacks = %d" % num_callbacks 139 | print(mystr) 140 | GPIO.remove_event_detect("XIO-P2") 141 | 142 | print("\nWAIT FOR EDGE TESTING, SETUP FOR FALLING EDGE") 143 | print("PRESS CONTROL-C TO EXIT IF SCRIPT GETS STUCK") 144 | try: 145 | # WAIT FOR EDGE 146 | t = threading.Thread(target=loopfunction) 147 | t.start() 148 | print("WAITING FOR EDGE ON XIO-P2") 149 | GPIO.wait_for_edge("XIO-P2", GPIO.FALLING) 150 | # THIS SHOULD ONLY PRINT IF WE'VE HIT THE EDGE DETECT 151 | print("WE'VE FALLEN LIKE COOLIO'S CAREER") 152 | except: 153 | pass 154 | 155 | print("Exit thread") 156 | loopfunction_exit = True 157 | t.join() # Wait till the thread exits. 158 | GPIO.remove_event_detect("XIO-P2") 159 | 160 | print("\n** BAD DAY SCENARIOS **") 161 | print(" ") 162 | print("TESTING ERRORS THROWN WHEN SPECIFYING EDGE DETECTION ON UNAUTHORIZED GPIO") 163 | GPIO.setup("CSID1", GPIO.IN) 164 | try: 165 | GPIO.add_event_detect("CSID1", GPIO.FALLING, myfuncallback) 166 | print(" Oops, it did not throw an exception! BUG!!!") 167 | num_errs += 1 168 | except ValueError, ex: 169 | mystr = " error msg = %s" % ex.args[0] 170 | print(mystr) 171 | pass 172 | except RuntimeError, ex: 173 | mystr = " error msg = %s" % ex.args[0] 174 | print(mystr) 175 | pass 176 | 177 | print("TESTING ERRORS THROWN WHEN SETTING UP AN ALREADY EXPORTED GPIO") 178 | try: 179 | GPIO.setup("CSID0", GPIO.LOW) 180 | print(" Oops, it did not throw an exception! BUG!!!") 181 | num_errs += 1 182 | except ValueError, ex: 183 | mystr = " error msg = %s" % ex.args[0] 184 | print(mystr) 185 | pass 186 | except RuntimeError, ex: 187 | mystr = " error msg = %s" % ex.args[0] 188 | print(mystr) 189 | pass 190 | 191 | print("TESTING ERRORS THROWN WHEN WRITING TO A GPIO NOT SET UP") 192 | try: 193 | GPIO.output("CSID2", GPIO.LOW) 194 | print(" Oops, it did not throw an exception! BUG!!!") 195 | num_errs += 1 196 | except ValueError, ex: 197 | mystr = " error msg = %s" % ex.args[0] 198 | print(mystr) 199 | pass 200 | except RuntimeError, ex: 201 | mystr = " error msg = %s" % ex.args[0] 202 | print(mystr) 203 | pass 204 | 205 | print("TESTING ERRORS THROWN WHEN WRITING TO A SET UP GPIO WITH NO DIRECTION") 206 | try: 207 | GPIO.output("CSID1", GPIO.LOW) 208 | print(" Oops, it did not throw an exception! BUG!!!") 209 | num_errs += 1 210 | except ValueError, ex: 211 | mystr = " error msg = %s" % ex.args[0] 212 | print(mystr) 213 | pass 214 | except RuntimeError, ex: 215 | mystr = " error msg = %s" % ex.args[0] 216 | print(mystr) 217 | pass 218 | 219 | print("TESTING ERRORS THROWN FOR ILLEGAL GPIO") 220 | try: 221 | GPIO.setup("NOTUSED", GPIO.IN) 222 | print(" Oops, it did not throw an exception! BUG!!!") 223 | num_errs += 1 224 | except ValueError, ex: 225 | mystr = " error msg = %s" % ex.args[0] 226 | print(mystr) 227 | pass 228 | except RuntimeError, ex: 229 | mystr = " error msg = %s" % ex.args[0] 230 | print(mystr) 231 | pass 232 | 233 | print("TESTING ERRORS THROWN FOR NON-GPIO") 234 | try: 235 | GPIO.setup("FEL", GPIO.IN) 236 | print(" Oops, it did not throw an exception! BUG!!!") 237 | num_errs += 1 238 | except ValueError, ex: 239 | mystr = " error msg = %s" % ex.args[0] 240 | print(mystr) 241 | pass 242 | except RuntimeError, ex: 243 | mystr = " error msg = %s" % ex.args[0] 244 | print(mystr) 245 | pass 246 | 247 | print("GPIO CLEANUP") 248 | GPIO.cleanup() 249 | 250 | mystr = "DONE: %d ERRORS" % num_errs 251 | print(mystr) 252 | -------------------------------------------------------------------------------- /docs/gpio.md: -------------------------------------------------------------------------------- 1 | ## CHIP_IO.GPIO 2 | Import the GPIO module as follows 3 | 4 | ```python 5 | import CHIP_IO.GPIO as GPIO 6 | ``` 7 | 8 | Note: As of version 0.7.0, all GPIO functions can use the SYSFS pin number for a GPIO for control, a la RPi.GPIO. 9 | 10 | ### toggle_debug() 11 | Enable/Disable the Debug 12 | 13 | * Parameters 14 | 15 | None 16 | 17 | * Examples 18 | 19 | ```python 20 | GPIO.toggle_debug() 21 | ``` 22 | 23 | ### is_chip_pro() 24 | Function to report to the calling script if the SBC is a CHIP or a CHIP Pro 25 | 26 | * Parameters 27 | 28 | None 29 | 30 | * Returns 31 | 32 | int - 1 for CHIP Pro, 0 for CHIP 33 | 34 | * Examples 35 | 36 | ```python 37 | is_chip_pro = GPIO.is_chip_pro() 38 | ``` 39 | 40 | ### setmode(mode) 41 | Dummy function to maintain backwards compatibility with Raspberry Pi scripts. 42 | 43 | ### setup(channel, direction, pull_up_down=PUD_OFF, initial=None) 44 | Setup a GPIO pin. If pin is already configure, it will reconfigure. 45 | 46 | * Parameters 47 | 48 | channel - GPIO pin 49 | direction - INPUT or OUTPUT 50 | pull_up_down - PUD_OFF, PUD_UP, PUD_DOWN (optional) 51 | initial - Initial value for an OUTPUT pin (optional) 52 | 53 | * Returns 54 | 55 | None 56 | 57 | * Examples 58 | 59 | ```python 60 | GPIO.setup("CSID0", GPIO.IN) 61 | GPIO.setup(132, GPIO.IN) 62 | GPIO.setup("CSID3", GPIO.OUT, initial=1) 63 | GPIO.setup("CSID2", GPIO.IN, GPIO.PUD_UP) 64 | ``` 65 | 66 | ### cleanup(channel) 67 | Cleanup GPIO. If not channel input, all GPIO will be cleaned up 68 | 69 | * Parameters 70 | 71 | channel - GPIO pin (optional) 72 | 73 | * Returns 74 | 75 | None 76 | 77 | * Examples 78 | 79 | ```python 80 | GPIO.cleanup() 81 | GPIO.cleanup("CSID3") 82 | GPIO.cleanup(132) 83 | ``` 84 | 85 | ### output(channel, value) 86 | Write a value to a GPIO pin. 87 | 88 | * Parameters 89 | 90 | channel - GPIO Pin 91 | value - HIGH, LOW, 0, 1 92 | 93 | * Returns 94 | 95 | None 96 | 97 | * Examples 98 | 99 | ```python 100 | GPIO.output("XIO-P7", GPIO.HIGH) 101 | GPIO.output("XIO-P7", GPIO.LOW) 102 | GPIO.output("CSID0", 1) 103 | GPIO.output("CSID0", 0) 104 | GPIO.output(132, 1) 105 | ``` 106 | 107 | ### input(channel) 108 | Read a GPIO pin once. 109 | 110 | * Parameters 111 | 112 | channel - GPIO Pin 113 | 114 | * Returns 115 | 116 | value - current value of the GPIO pin 117 | 118 | * Examples 119 | 120 | ```python 121 | value = GPIO.input("XIO-P7") 122 | value = GPIO.input(1013) 123 | ``` 124 | 125 | ### read_byte(channel) 126 | Read a GPIO pin multiple times to fill up 8 bits. 127 | 128 | * Parameters 129 | 130 | channel - GPIO Pin 131 | 132 | * Returns 133 | 134 | int - 8 bit value of the GPIO pin 135 | 136 | * Examples 137 | 138 | ```python 139 | bits = GPIO.read_byte("XIO-P7") 140 | bits = GPIO.read_byte(135) 141 | ``` 142 | 143 | ### read_word(channel) 144 | Read a GPIO pin multiple times to fill up 16 bits. 145 | 146 | * Parameters 147 | 148 | channel - GPIO Pin 149 | 150 | * Returns 151 | 152 | word - 16 bit value of the GPIO pin 153 | 154 | * Examples 155 | 156 | ```python 157 | bits = GPIO.read_word("XIO-P7") 158 | bits = GPIO.read_word(134) 159 | ``` 160 | 161 | ### add_event_detect(channel, edge, callback=None, bouncetime=0) 162 | Add event detection to a pin. Refer to main table for which pins are able to use edge detection. 163 | 164 | * Parameters 165 | 166 | channel - GPIO Pin 167 | edge - edge: RISING_EDGE, FALLING_EDGE, BOTH_EDGE 168 | callback - callback function to be run when edge is detected (optional) 169 | bouncetime - level debounce time period in ms (optional) 170 | 171 | * Returns 172 | 173 | None 174 | 175 | * Examples 176 | 177 | ```python 178 | GPIO.add_event_detect("XIO-P7", GPIO.RISING_EDGE) 179 | GPIO.add_event_detect("AP-EINT3", GPIO.RISING_EDGE, mycallback) 180 | GPIO.add_event_detect("XIO-P7", GPIO.FALLING_EDGE, bouncetime=30) 181 | GPIO.add_event_detect("XIO-P7", GPIO.RISING_EDGE, mycallback, 45) 182 | GPIO.add_event_detect(1013, GPIO.BOTH_EDGE) 183 | ``` 184 | 185 | ### remove_event_detect(channel) 186 | Remove a pins event detection. Refer to main table for which pins are able to use edge detection. 187 | 188 | * Parameters 189 | 190 | channel - GPIO Pin 191 | 192 | * Returns 193 | 194 | None 195 | 196 | * Examples 197 | 198 | ```python 199 | GPIO.remove_event_detect("XIO-P7") 200 | GPIO.remove_event_detect(1013) 201 | ``` 202 | 203 | ### event_detected(channel) 204 | Function to determine if an event was detected on a pin. Pin must have an event detect added via add_event_detect() prior to calling this function. Refer to main table for which pins are able to use edge detection. 205 | 206 | * Parameters 207 | 208 | channel - GPIO Pin 209 | 210 | * Returns 211 | 212 | boolean - True if event was detected 213 | 214 | * Examples 215 | 216 | ```python 217 | have_event = GPIO.event_detected("XIO-P5") 218 | have_event = GPIO.event_detected(1014) 219 | ``` 220 | 221 | ### add_event_callback(channel, callback, bouncetime=0) 222 | Add callback function to a pin that has been setup for edge detection. Refer to main table for which pins are able to use edge detection. 223 | 224 | * Parameters 225 | 226 | channel - GPIO Pin 227 | callback - callback function to be run when edge is detected 228 | bouncetime - level debounce time period in ms (optional) 229 | 230 | * Returns 231 | 232 | None 233 | 234 | * Examples 235 | 236 | ```python 237 | GPIO.add_event_callback("AP-EINT3", mycallback) 238 | GPIO.add_event_callback("XIO-P7", mycallback, 45) 239 | GPIO.add_event_callback(1013, mycallback) 240 | ``` 241 | 242 | ### wait_for_edge(channel, edge, timeout=-1) 243 | Wait for an edge to be detected. This is a blocking function. Refer to main table for which pins are able to use edge detection. 244 | 245 | * Parameters 246 | 247 | channel - GPIO Pin 248 | edge - edge: RISING_EDGE, FALLING_EDGE, BOTH_EDGE 249 | timeout - timeout in milliseconds to wait before exiting function (optional) 250 | 251 | * Returns 252 | 253 | None 254 | 255 | * Examples 256 | 257 | ```python 258 | GPIO.wait_for_edge("XIO-P3", GPIO.RISING_EDGE) 259 | GPIO.wait_for_edge("AP-EINT3", GPIO.BOTH_EDGE) 260 | GPIO.wait_for_edge("I2S-DI", GPIO.FALLING_EDGE) 261 | GPIO.wait_for_edge("XIO-P3", GPIO.RISING_EDGE, 40) 262 | GPIO.wait_for_edge(1013, GPIO.BOTH_EDGE, 35) 263 | ``` 264 | 265 | ### gpio_function(channel) 266 | Function to report get a GPIO Pins directioj 267 | 268 | * Parameters 269 | 270 | channel - GPIO Pin 271 | 272 | * Returns 273 | 274 | int - GPIO Pin direction 275 | 276 | * Examples 277 | 278 | ```python 279 | funct = GPIO.gpio_function("CSID0") 280 | funct = GPIO.gpio_function(132) 281 | ``` 282 | 283 | ### setwarnings(state) 284 | Function to enable/disable warning print outs. This may or may not work properly. toggle_debug() is a better bet. 285 | 286 | * Parameters 287 | 288 | state - 1 for enable, 0 for disable 289 | 290 | * Returns 291 | 292 | None 293 | 294 | * Examples 295 | 296 | ```python 297 | GPIO.set_warnings(1) 298 | ``` 299 | 300 | ### get_gpio_base() 301 | Function to get the SYSFS base value for the XIO pins on a CHIP 302 | 303 | * Parameters 304 | 305 | None 306 | 307 | * Returns 308 | 309 | int - sysfs base of the XIO, returns -1 on a CHIP Pro 310 | 311 | * Examples 312 | 313 | ```python 314 | base = GPIO.get_gpio_base() 315 | ``` 316 | 317 | ### selftest(value) 318 | Function to perform a selftest on the GPIO module 319 | 320 | * Parameters 321 | 322 | value - a value 323 | 324 | * Returns 325 | 326 | int - the input value 327 | 328 | * Examples 329 | 330 | ```python 331 | rtn = GPIO.selftest(0) 332 | ``` 333 | 334 | ### direction(channel, direction) 335 | Function to set the direction of an exported GPIO pin 336 | 337 | * Parameters 338 | 339 | channel - GPIO Pin 340 | direction - Direction Pin is to take 341 | 342 | * Returns 343 | 344 | None 345 | 346 | * Examples 347 | 348 | ```python 349 | GPIO.set_direction("XIO-P0", GPIO.OUT) 350 | GPIO.set_direction("XIO-P1", GPIO.IN) 351 | GPIO.set_direction(1013, GPIO.OUT) 352 | ``` 353 | 354 | [home](./index.md) 355 | -------------------------------------------------------------------------------- /source/c_softpwm.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Brady Hurlburt 3 | 4 | Original BBIO Author Justin Cooper 5 | Modified for CHIP_IO Author Brady Hurlburt 6 | 7 | This file incorporates work covered by the following copyright and 8 | permission notice, all modified code adopts the original license: 9 | 10 | Copyright (c) 2013 Adafruit 11 | Author: Justin Cooper 12 | 13 | Permission is hereby granted, free of charge, to any person obtaining a copy of 14 | this software and associated documentation files (the "Software"), to deal in 15 | the Software without restriction, including without limitation the rights to 16 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 17 | of the Software, and to permit persons to whom the Software is furnished to do 18 | so, subject to the following conditions: 19 | 20 | The above copyright notice and this permission notice shall be included in all 21 | copies or substantial portions of the Software. 22 | 23 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 24 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 25 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 26 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 27 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 28 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 29 | SOFTWARE. 30 | */ 31 | 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include "c_softpwm.h" 43 | #include "common.h" 44 | #include "event_gpio.h" 45 | 46 | #define KEYLEN 7 47 | 48 | #define PERIOD 0 49 | #define DUTY 1 50 | 51 | int pwm_initialized = 0; 52 | 53 | struct pwm_params 54 | { 55 | float duty; 56 | float freq; 57 | bool enabled; 58 | bool stop_flag; 59 | int polarity; 60 | }; 61 | 62 | struct softpwm 63 | { 64 | char key[KEYLEN+1]; /* leave room for terminating NUL byte */ 65 | int gpio; 66 | struct pwm_params params; 67 | pthread_mutex_t* params_lock; 68 | pthread_t thread; 69 | struct softpwm *next; 70 | }; 71 | struct softpwm *exported_pwms = NULL; 72 | 73 | struct softpwm *lookup_exported_pwm(const char *key) 74 | { 75 | struct softpwm *pwm = exported_pwms; 76 | 77 | while (pwm != NULL) 78 | { 79 | if (strcmp(pwm->key, key) == 0) { 80 | return pwm; 81 | } 82 | pwm = pwm->next; 83 | } 84 | 85 | return NULL; /* standard for pointers */ 86 | } 87 | 88 | int softpwm_set_frequency(const char *key, float freq) { 89 | struct softpwm *pwm; 90 | 91 | if (freq <= 0.0) 92 | return -1; 93 | 94 | pwm = lookup_exported_pwm(key); 95 | 96 | if (pwm == NULL) { 97 | return -1; 98 | } 99 | 100 | if (DEBUG) 101 | printf(" ** softpwm_set_frequency: %f **\n", freq); 102 | pthread_mutex_lock(pwm->params_lock); 103 | pwm->params.freq = freq; 104 | pthread_mutex_unlock(pwm->params_lock); 105 | 106 | return 0; 107 | } 108 | 109 | int softpwm_set_polarity(const char *key, int polarity) { 110 | struct softpwm *pwm; 111 | 112 | pwm = lookup_exported_pwm(key); 113 | 114 | if (pwm == NULL) { 115 | return -1; 116 | } 117 | 118 | if (polarity < 0 || polarity > 1) { 119 | return -1; 120 | } 121 | 122 | if (DEBUG) 123 | printf(" ** softpwm_set_polarity: %d **\n", polarity); 124 | pthread_mutex_lock(pwm->params_lock); 125 | pwm->params.polarity = polarity; 126 | pthread_mutex_unlock(pwm->params_lock); 127 | 128 | return 0; 129 | } 130 | 131 | int softpwm_set_duty_cycle(const char *key, float duty) {; 132 | struct softpwm *pwm; 133 | 134 | if (duty < 0.0 || duty > 100.0) 135 | return -1; 136 | 137 | pwm = lookup_exported_pwm(key); 138 | 139 | if (pwm == NULL) { 140 | return -1; 141 | } 142 | 143 | if (DEBUG) 144 | printf(" ** softpwm_set_duty_cycle: %f **\n", duty); 145 | pthread_mutex_lock(pwm->params_lock); 146 | pwm->params.duty = duty; 147 | pthread_mutex_unlock(pwm->params_lock); 148 | 149 | return 0; 150 | } 151 | 152 | void *softpwm_thread_toggle(void *arg) 153 | { 154 | struct softpwm *pwm = (struct softpwm *)arg; 155 | int gpio = pwm->gpio; 156 | struct timespec tim_on; 157 | struct timespec tim_off; 158 | unsigned int sec; 159 | unsigned int period_ns; 160 | unsigned int on_ns; 161 | unsigned int off_ns; 162 | 163 | /* Used to determine if something has 164 | * has changed 165 | */ 166 | float freq_local = 0; 167 | float duty_local = 0; 168 | unsigned int polarity_local = 0; 169 | bool stop_flag_local = false; 170 | bool enabled_local = false; 171 | bool recalculate_timing = false; 172 | 173 | while (!stop_flag_local) { 174 | /* Take a snapshot of the parameter block */ 175 | pthread_mutex_lock(pwm->params_lock); 176 | if ((freq_local != pwm->params.freq) || (duty_local != pwm->params.duty)) { 177 | recalculate_timing = true; 178 | } 179 | freq_local = pwm->params.freq; 180 | duty_local = pwm->params.duty; 181 | enabled_local = pwm->params.enabled; 182 | stop_flag_local = pwm->params.stop_flag; 183 | polarity_local = pwm->params.polarity; 184 | pthread_mutex_unlock(pwm->params_lock); 185 | 186 | /* If freq or duty has been changed, update the 187 | * sleep times 188 | */ 189 | if (recalculate_timing) { 190 | period_ns = (unsigned long)(1e9 / freq_local); 191 | on_ns = (unsigned long)(period_ns * (duty_local/100)); 192 | off_ns = period_ns - on_ns; 193 | sec = (unsigned int)(on_ns/1e9); /* Intentional truncation */ 194 | tim_on.tv_sec = sec; 195 | tim_on.tv_nsec = on_ns - (sec*1e9); 196 | sec = (unsigned int)(off_ns/1e9); /* Intentional truncation */ 197 | tim_off.tv_sec = sec; 198 | tim_off.tv_nsec = off_ns - (sec*1e9); 199 | recalculate_timing = false; 200 | } 201 | 202 | if (enabled_local) 203 | { 204 | /* Force 0 duty cycle to be 0 */ 205 | if (duty_local != 0) 206 | { 207 | /* Set gpio */ 208 | if (!polarity_local) 209 | gpio_set_value(gpio, HIGH); 210 | else 211 | gpio_set_value(gpio, LOW); 212 | } 213 | 214 | nanosleep(&tim_on, NULL); 215 | 216 | /* Force 100 duty cycle to be 100 */ 217 | if (duty_local != 100) 218 | { 219 | /* Unset gpio */ 220 | if (!polarity_local) 221 | gpio_set_value(gpio, LOW); 222 | else 223 | gpio_set_value(gpio, HIGH); 224 | } 225 | 226 | nanosleep(&tim_off, NULL); 227 | } /* if enabled_local */ 228 | } /* while !stop_flag_local */ 229 | 230 | if (!polarity_local) 231 | gpio_set_value(gpio, LOW); 232 | else 233 | gpio_set_value(gpio, HIGH); 234 | 235 | /* This pwm has been disabled */ 236 | pthread_exit(NULL); 237 | } 238 | 239 | int softpwm_start(const char *key, float duty, float freq, int polarity) 240 | { 241 | struct softpwm *new_pwm, *pwm; 242 | pthread_t new_thread; 243 | pthread_mutex_t *new_params_lock; 244 | int gpio; 245 | int ret; 246 | 247 | if (get_gpio_number(key, &gpio) < 0) { 248 | if (DEBUG) 249 | printf(" ** softpwm_start: invalid gpio specified **\n"); 250 | return -1; 251 | } 252 | 253 | if (gpio_export(gpio) < 0) { 254 | char err[2000]; 255 | snprintf(err, sizeof(err), "Error setting up softpwm on pin %d, maybe already exported? (%s)", gpio, get_error_msg()); 256 | add_error_msg(err); 257 | return -1; 258 | } 259 | 260 | if (DEBUG) 261 | printf(" ** softpwm_start: %d exported **\n", gpio); 262 | 263 | if (gpio_set_direction(gpio, OUTPUT) < 0) { 264 | if (DEBUG) 265 | printf(" ** softpwm_start: gpio_set_direction failed **\n"); 266 | return -1; 267 | } 268 | 269 | // add to list 270 | new_pwm = malloc(sizeof(struct softpwm)); ASSRT(new_pwm != NULL); 271 | new_params_lock = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t)); 272 | if (new_pwm == 0) { 273 | return -1; // out of memory 274 | } 275 | pthread_mutex_init(new_params_lock, NULL); 276 | pthread_mutex_lock(new_params_lock); 277 | 278 | strncpy(new_pwm->key, key, KEYLEN); /* can leave string unterminated */ 279 | new_pwm->key[KEYLEN] = '\0'; /* terminate string */ 280 | new_pwm->gpio = gpio; 281 | new_pwm->params.enabled = true; 282 | new_pwm->params.stop_flag = false; 283 | new_pwm->params_lock = new_params_lock; 284 | new_pwm->next = NULL; 285 | 286 | if (exported_pwms == NULL) 287 | { 288 | // create new list 289 | exported_pwms = new_pwm; 290 | } else { 291 | // add to end of existing list 292 | pwm = exported_pwms; 293 | while (pwm->next != NULL) 294 | pwm = pwm->next; 295 | pwm->next = new_pwm; 296 | } 297 | pthread_mutex_unlock(new_params_lock); 298 | 299 | if (DEBUG) 300 | printf(" ** softpwm_enable: setting softpwm parameters **\n"); 301 | ASSRT(softpwm_set_duty_cycle(new_pwm->key, duty) == 0); 302 | ASSRT(softpwm_set_frequency(new_pwm->key, freq) == 0); 303 | ASSRT(softpwm_set_polarity(new_pwm->key, polarity) == 0); 304 | 305 | pthread_mutex_lock(new_params_lock); 306 | // create thread for pwm 307 | if (DEBUG) 308 | printf(" ** softpwm_enable: creating thread **\n"); 309 | ret = pthread_create(&new_thread, NULL, softpwm_thread_toggle, (void *)new_pwm); 310 | ASSRT(ret == 0); 311 | 312 | new_pwm->thread = new_thread; 313 | 314 | pthread_mutex_unlock(new_params_lock); 315 | 316 | return 1; 317 | } 318 | 319 | int softpwm_disable(const char *key) 320 | { 321 | struct softpwm *pwm, *temp, *prev_pwm = NULL; 322 | 323 | if (DEBUG) 324 | printf(" ** in softpwm_disable **\n"); 325 | // remove from list 326 | pwm = exported_pwms; 327 | while (pwm != NULL) 328 | { 329 | if (strcmp(pwm->key, key) == 0) 330 | { 331 | if (DEBUG) 332 | printf(" ** softpwm_disable: found pin **\n"); 333 | pthread_mutex_lock(pwm->params_lock); 334 | pwm->params.stop_flag = true; 335 | pthread_mutex_unlock(pwm->params_lock); 336 | pthread_join(pwm->thread, NULL); /* wait for thread to exit */ 337 | 338 | if (DEBUG) 339 | printf(" ** softpwm_disable: unexporting %d **\n", pwm->gpio); 340 | gpio_unexport(pwm->gpio); 341 | 342 | if (prev_pwm == NULL) 343 | { 344 | exported_pwms = pwm->next; 345 | prev_pwm = pwm; 346 | } else { 347 | prev_pwm->next = pwm->next; 348 | } 349 | 350 | temp = pwm; 351 | pwm = pwm->next; 352 | free(temp->params_lock); 353 | free(temp); 354 | } else { 355 | prev_pwm = pwm; 356 | pwm = pwm->next; 357 | } 358 | } 359 | return 0; 360 | } 361 | 362 | void softpwm_cleanup(void) 363 | { 364 | while (exported_pwms != NULL) { 365 | softpwm_disable(exported_pwms->key); 366 | } 367 | } 368 | -------------------------------------------------------------------------------- /source/c_softservo.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017 Robert Wolterman 3 | 4 | Using CHIP_IO servo code from Brady Hurlburt as a basis for the servo code 5 | 6 | Copyright (c) 2016 Brady Hurlburt 7 | 8 | Original BBIO Author Justin Cooper 9 | Modified for CHIP_IO Author Brady Hurlburt 10 | 11 | This file incorporates work covered by the following copyright and 12 | permission notice, all modified code adopts the original license: 13 | 14 | Copyright (c) 2013 Adafruit 15 | Author: Justin Cooper 16 | 17 | Permission is hereby granted, free of charge, to any person obtaining a copy of 18 | this software and associated documentation files (the "Software"), to deal in 19 | the Software without restriction, including without limitation the rights to 20 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 21 | of the Software, and to permit persons to whom the Software is furnished to do 22 | so, subject to the following conditions: 23 | 24 | The above copyright notice and this permission notice shall be included in all 25 | copies or substantial portions of the Software. 26 | 27 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 28 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 29 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 30 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 31 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 32 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 33 | SOFTWARE. 34 | */ 35 | 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | #include "c_softservo.h" 47 | #include "common.h" 48 | #include "event_gpio.h" 49 | 50 | #define KEYLEN 7 51 | 52 | #define PERIOD 0 53 | #define DUTY 1 54 | 55 | #define MSTONS 1000000 56 | #define BLOCKNS 20 * MSTONS 57 | #define FUDGEFACTOR 450 58 | #define MSTOMICROS 1000 59 | #define MICROSTONS 1000 60 | #define MINMICROS 1000 61 | #define NEUTRAL 1500 62 | #define MAXMICROS 2000 63 | 64 | int servo_initialized = 0; 65 | 66 | struct servo_params 67 | { 68 | float range; 69 | float min_angle; 70 | float max_angle; 71 | float current_angle; 72 | bool enabled; 73 | bool stop_flag; 74 | }; 75 | 76 | struct servo 77 | { 78 | char key[KEYLEN+1]; /* leave room for terminating NUL byte */ 79 | int gpio; 80 | struct servo_params params; 81 | pthread_mutex_t* params_lock; 82 | pthread_t thread; 83 | struct servo *next; 84 | }; 85 | struct servo *exported_servos = NULL; 86 | 87 | struct servo *lookup_exported_servo(const char *key) 88 | { 89 | struct servo *srv = exported_servos; 90 | 91 | while (srv != NULL) 92 | { 93 | if (strcmp(srv->key, key) == 0) { 94 | return srv; 95 | } 96 | srv = srv->next; 97 | } 98 | 99 | return NULL; /* standard for pointers */ 100 | } 101 | 102 | void *servo_thread_toggle(void *arg) 103 | { 104 | struct servo *srv = (struct servo *)arg; 105 | int gpio = srv->gpio; 106 | struct timespec tim_on; 107 | struct timespec tim_off; 108 | float on_time_microsec = 0; 109 | unsigned int on_ns; 110 | unsigned int off_ns; 111 | 112 | /* Used to determine if something has 113 | * has changed 114 | */ 115 | float angle_local = 0; 116 | float range_local = 0; 117 | bool stop_flag_local = false; 118 | bool enabled_local = false; 119 | bool recalculate_timing = false; 120 | 121 | while (!stop_flag_local) { 122 | /* Take a snapshot of the parameter block */ 123 | pthread_mutex_lock(srv->params_lock); 124 | if ((angle_local != srv->params.current_angle) || (range_local != srv->params.range)) { 125 | recalculate_timing = true; 126 | } 127 | angle_local = srv->params.current_angle; 128 | range_local = srv->params.range; 129 | enabled_local = srv->params.enabled; 130 | stop_flag_local = srv->params.stop_flag; 131 | pthread_mutex_unlock(srv->params_lock); 132 | 133 | /* If freq or duty has been changed, update the 134 | * sleep times 135 | */ 136 | if (recalculate_timing) { 137 | if (DEBUG) 138 | printf(" ** servo updating timing: new angle: (%.2f)\n",angle_local); 139 | on_time_microsec = (((MAXMICROS - MINMICROS) / range_local) * angle_local) + NEUTRAL; 140 | on_ns = (unsigned long)(on_time_microsec * MICROSTONS - FUDGEFACTOR); 141 | off_ns = BLOCKNS - on_ns; 142 | tim_on.tv_sec = 0; 143 | tim_on.tv_nsec = on_ns; 144 | tim_off.tv_sec = 0; 145 | tim_off.tv_nsec = off_ns; 146 | recalculate_timing = false; 147 | } 148 | 149 | if (enabled_local) 150 | { 151 | /* Set gpio */ 152 | gpio_set_value(gpio, HIGH); 153 | 154 | nanosleep(&tim_on, NULL); 155 | 156 | /* Unset gpio */ 157 | gpio_set_value(gpio, LOW); 158 | 159 | nanosleep(&tim_off, NULL); 160 | //printf("AFTER SECOND NANOSLEEP\n"); 161 | } /* if enabled_local */ 162 | } /* while !stop_flag_local */ 163 | 164 | gpio_set_value(gpio, LOW); 165 | 166 | /* This servo has been disabled */ 167 | pthread_exit(NULL); 168 | } 169 | 170 | int servo_start(const char *key, float angle, float range) 171 | { 172 | struct servo *new_srv, *srv; 173 | pthread_t new_thread; 174 | pthread_mutex_t *new_params_lock; 175 | int gpio; 176 | int ret; 177 | 178 | if (get_gpio_number(key, &gpio) < 0) { 179 | if (DEBUG) 180 | printf(" ** servo_start: invalid gpio specified **\n"); 181 | return -1; 182 | } 183 | 184 | if (gpio_export(gpio) < 0) { 185 | char err[2000]; 186 | snprintf(err, sizeof(err), "Error setting up servo on pin %d, maybe already exported? (%s)", gpio, get_error_msg()); 187 | add_error_msg(err); 188 | return -1; 189 | } 190 | 191 | if (DEBUG) 192 | printf(" ** servo_start: %d exported **\n", gpio); 193 | 194 | if (gpio_set_direction(gpio, OUTPUT) < 0) { 195 | if (DEBUG) 196 | printf(" ** servo_start: gpio_set_direction failed **\n"); 197 | return -1; 198 | } 199 | 200 | printf("c_softservo.c: servo_start(%d,%.2f,%.2f)\n",gpio,angle,range); 201 | 202 | // add to list 203 | new_srv = malloc(sizeof(struct servo)); ASSRT(new_srv != NULL); 204 | new_params_lock = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t)); 205 | if (new_srv == 0) { 206 | return -1; // out of memory 207 | } 208 | pthread_mutex_init(new_params_lock, NULL); 209 | pthread_mutex_lock(new_params_lock); 210 | 211 | strncpy(new_srv->key, key, KEYLEN); /* can leave string unterminated */ 212 | new_srv->key[KEYLEN] = '\0'; /* terminate string */ 213 | new_srv->gpio = gpio; 214 | new_srv->params.enabled = true; 215 | new_srv->params.stop_flag = false; 216 | new_srv->params_lock = new_params_lock; 217 | new_srv->next = NULL; 218 | 219 | if (exported_servos == NULL) 220 | { 221 | // create new list 222 | exported_servos = new_srv; 223 | } else { 224 | // add to end of existing list 225 | srv = exported_servos; 226 | while (srv->next != NULL) 227 | srv = srv->next; 228 | srv->next = new_srv; 229 | } 230 | pthread_mutex_unlock(new_params_lock); 231 | 232 | if (DEBUG) 233 | printf(" ** servo_enable: setting servo parameters **\n"); 234 | ASSRT(servo_set_range(new_srv->key, range) == 0); 235 | ASSRT(servo_set_angle(new_srv->key, angle) == 0); 236 | 237 | pthread_mutex_lock(new_params_lock); 238 | // create thread for srv 239 | if (DEBUG) 240 | printf(" ** servo_enable: creating thread **\n"); 241 | ret = pthread_create(&new_thread, NULL, servo_thread_toggle, (void *)new_srv); 242 | ASSRT(ret == 0); 243 | 244 | new_srv->thread = new_thread; 245 | 246 | pthread_mutex_unlock(new_params_lock); 247 | 248 | return 1; 249 | } 250 | 251 | int servo_disable(const char *key) 252 | { 253 | struct servo *srv, *temp, *prev_srv = NULL; 254 | 255 | if (DEBUG) 256 | printf(" ** in servo_disable **\n"); 257 | // remove from list 258 | srv = exported_servos; 259 | while (srv != NULL) 260 | { 261 | if (strcmp(srv->key, key) == 0) 262 | { 263 | if (DEBUG) 264 | printf(" ** servo_disable: found pin **\n"); 265 | pthread_mutex_lock(srv->params_lock); 266 | srv->params.stop_flag = true; 267 | pthread_mutex_unlock(srv->params_lock); 268 | pthread_join(srv->thread, NULL); /* wait for thread to exit */ 269 | 270 | if (DEBUG) 271 | printf(" ** servo_disable: unexporting %d **\n", srv->gpio); 272 | gpio_unexport(srv->gpio); 273 | 274 | if (prev_srv == NULL) 275 | { 276 | exported_servos = srv->next; 277 | prev_srv = srv; 278 | } else { 279 | prev_srv->next = srv->next; 280 | } 281 | 282 | temp = srv; 283 | srv = srv->next; 284 | free(temp->params_lock); 285 | free(temp); 286 | } else { 287 | prev_srv = srv; 288 | srv = srv->next; 289 | } 290 | } 291 | return 0; 292 | } 293 | 294 | int servo_set_range(const char *key, float range) 295 | { 296 | struct servo *srv; 297 | float min_angle, max_angle; 298 | 299 | srv = lookup_exported_servo(key); 300 | 301 | if (srv == NULL) { 302 | return -1; 303 | } 304 | 305 | // Compute the min and max angle 306 | max_angle = range / 2.0; 307 | min_angle = -max_angle; 308 | 309 | if (DEBUG) 310 | printf(" ** servo_set_range(%d,%.2f = %.2f,%.2f)\n",srv->gpio,range,min_angle,max_angle); 311 | pthread_mutex_lock(srv->params_lock); 312 | srv->params.range = range; 313 | srv->params.min_angle = min_angle; 314 | srv->params.max_angle = max_angle; 315 | pthread_mutex_unlock(srv->params_lock); 316 | 317 | return 0; 318 | } 319 | 320 | int servo_set_angle(const char *key, float angle) 321 | { 322 | struct servo *srv; 323 | 324 | srv = lookup_exported_servo(key); 325 | 326 | if (srv == NULL) { 327 | return -1; 328 | } 329 | 330 | // Make sure we're between the range of allowable angles 331 | if (angle < srv->params.min_angle || angle > srv->params.max_angle) { 332 | char err[2000]; 333 | snprintf(err, sizeof(err), "Angle specified (%.2f) for pin %d, is outside allowable range (%.2f,%.2f)", angle, srv->gpio, srv->params.min_angle,srv->params.max_angle); 334 | add_error_msg(err); 335 | return -1; 336 | } 337 | 338 | if (DEBUG) 339 | printf(" ** servo_set_angle(%d,%.2f)\n",srv->gpio,angle); 340 | pthread_mutex_lock(srv->params_lock); 341 | srv->params.current_angle = angle; 342 | pthread_mutex_unlock(srv->params_lock); 343 | 344 | return 0; 345 | } 346 | 347 | void servo_cleanup(void) 348 | { 349 | while (exported_servos != NULL) { 350 | servo_disable(exported_servos->key); 351 | } 352 | } 353 | 354 | 355 | 356 | -------------------------------------------------------------------------------- /source/py_servo.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017 Robert Wolterman 3 | 4 | Using CHIP_IO servo code from Brady Hurlburt as a basis for the servo code 5 | 6 | Copyright (c) 2016 Brady Hurlburt 7 | 8 | Original BBIO Author Justin Cooper 9 | Modified for CHIP_IO Author Brady Hurlburt 10 | 11 | This file incorporates work covered by the following copyright and 12 | permission notice, all modified code adopts the original license: 13 | 14 | Copyright (c) 2013 Adafruit 15 | Author: Justin Cooper 16 | 17 | Permission is hereby granted, free of charge, to any person obtaining a copy of 18 | this software and associated documentation files (the "Software"), to deal in 19 | the Software without restriction, including without limitation the rights to 20 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 21 | of the Software, and to permit persons to whom the Software is furnished to do 22 | so, subject to the following conditions: 23 | 24 | The above copyright notice and this permission notice shall be included in all 25 | copies or substantial portions of the Software. 26 | 27 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 28 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 29 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 30 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 31 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 32 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 33 | SOFTWARE. 34 | */ 35 | 36 | #include "Python.h" 37 | #include "constants.h" 38 | #include "common.h" 39 | #include "c_softservo.h" 40 | 41 | // python function toggle_debug() 42 | static PyObject *py_toggle_debug(PyObject *self, PyObject *args) 43 | { 44 | // toggle debug printing 45 | toggle_debug(); 46 | 47 | Py_RETURN_NONE; 48 | } 49 | 50 | // python function cleanup() 51 | static PyObject *py_cleanup(PyObject *self, PyObject *args) 52 | { 53 | // TODO: PER PIN CLEANUP LIKE EVERYTHING ELSE 54 | 55 | // unexport the Servo 56 | servo_cleanup(); 57 | 58 | Py_RETURN_NONE; 59 | } 60 | 61 | static int init_module(void) 62 | { 63 | clear_error_msg(); 64 | 65 | // If we make it here, we're good to go 66 | if (DEBUG) 67 | printf(" ** init_module: setup complete **\n"); 68 | module_setup = 1; 69 | 70 | return 0; 71 | } 72 | 73 | // python function value = is_chip_pro() 74 | static PyObject *py_is_chip_pro(PyObject *self, PyObject *args) 75 | { 76 | PyObject *py_value; 77 | 78 | py_value = Py_BuildValue("i", is_this_chippro()); 79 | 80 | return py_value; 81 | } 82 | 83 | // python function start(channel, angle, range) 84 | static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwargs) 85 | { 86 | int gpio; 87 | char key[8]; 88 | char *channel = NULL; 89 | float angle = 0.0; 90 | float range = 180.0; 91 | int allowed = -1; 92 | static char *kwlist[] = {"channel", "angle", "range", NULL}; 93 | 94 | clear_error_msg(); 95 | 96 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|ff", kwlist, &channel, &angle, &range)) { 97 | return NULL; 98 | } 99 | ASSRT(channel != NULL); 100 | 101 | if (!module_setup) { 102 | init_module(); 103 | } 104 | 105 | if (!get_key(channel, key)) { 106 | PyErr_SetString(PyExc_ValueError, "Invalid Servo key or name."); 107 | return NULL; 108 | } 109 | 110 | // check to ensure gpio is one of the allowed pins 111 | // Not protecting the call as if the get_key() fails, we won't make it here 112 | get_gpio_number(channel, &gpio); 113 | if ((gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) { 114 | PyErr_SetString(PyExc_ValueError, "Servo currently not available on XIO-P0 to XIO-P7"); 115 | return NULL; 116 | } 117 | 118 | // Check to see if GPIO is allowed on the hardware 119 | // A 1 means we're good to go 120 | allowed = gpio_allowed(gpio); 121 | if (allowed == -1) { 122 | char err[2000]; 123 | snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg()); 124 | PyErr_SetString(PyExc_ValueError, err); 125 | return NULL; 126 | } else if (allowed == 0) { 127 | char err[2000]; 128 | snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio); 129 | PyErr_SetString(PyExc_ValueError, err); 130 | return NULL; 131 | } 132 | 133 | if (servo_start(key, angle, range) < 0) { 134 | printf("servo_start failed"); 135 | char err[2000]; 136 | snprintf(err, sizeof(err), "Error starting servo on pin %s (%s)", key, get_error_msg()); 137 | PyErr_SetString(PyExc_RuntimeError, err); 138 | return NULL; 139 | } 140 | 141 | Py_RETURN_NONE; 142 | } 143 | 144 | // python function stop(channel) 145 | static PyObject *py_stop_channel(PyObject *self, PyObject *args, PyObject *kwargs) 146 | { 147 | int gpio; 148 | char key[8]; 149 | int allowed = -1; 150 | char *channel; 151 | 152 | clear_error_msg(); 153 | 154 | if (!PyArg_ParseTuple(args, "s", &channel)) 155 | return NULL; 156 | 157 | if (!get_key(channel, key)) { 158 | PyErr_SetString(PyExc_ValueError, "Invalid key or name"); 159 | return NULL; 160 | } 161 | 162 | // check to ensure gpio is one of the allowed pins 163 | // Not protecting the call as if the get_key() fails, we won't make it here 164 | get_gpio_number(channel, &gpio); 165 | if ((gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) { 166 | PyErr_SetString(PyExc_ValueError, "Servo currently not available on XIO-P0 to XIO-P7"); 167 | return NULL; 168 | } 169 | 170 | // Check to see if GPIO is allowed on the hardware 171 | // A 1 means we're good to go 172 | allowed = gpio_allowed(gpio); 173 | if (allowed == -1) { 174 | char err[2000]; 175 | snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg()); 176 | PyErr_SetString(PyExc_ValueError, err); 177 | return NULL; 178 | } else if (allowed == 0) { 179 | char err[2000]; 180 | snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio); 181 | PyErr_SetString(PyExc_ValueError, err); 182 | return NULL; 183 | } 184 | 185 | servo_disable(key); 186 | 187 | Py_RETURN_NONE; 188 | } 189 | 190 | // python method SERVO.set_range(channel, range) 191 | static PyObject *py_set_range(PyObject *self, PyObject *args, PyObject *kwargs) 192 | { 193 | int gpio; 194 | char key[8]; 195 | char *channel; 196 | float range = 180.0; 197 | int allowed = -1; 198 | static char *kwlist[] = {"channel", "range", NULL}; 199 | 200 | clear_error_msg(); 201 | 202 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &range)) 203 | return NULL; 204 | 205 | if (range > 360.0) { 206 | PyErr_SetString(PyExc_ValueError, "range can not be greater than 360.0"); 207 | return NULL; 208 | } 209 | 210 | if (!get_key(channel, key)) { 211 | PyErr_SetString(PyExc_ValueError, "Invalid key or name."); 212 | return NULL; 213 | } 214 | 215 | // check to ensure gpio is one of the allowed pins 216 | // Not protecting the call as if the get_key() fails, we won't make it here 217 | get_gpio_number(channel, &gpio); 218 | if ((gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) { 219 | PyErr_SetString(PyExc_ValueError, "Servo currently not available on XIO-P0 to XIO-P7"); 220 | return NULL; 221 | } 222 | 223 | // Check to see if GPIO is allowed on the hardware 224 | // A 1 means we're good to go 225 | allowed = gpio_allowed(gpio); 226 | if (allowed == -1) { 227 | char err[2000]; 228 | snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg()); 229 | PyErr_SetString(PyExc_ValueError, err); 230 | return NULL; 231 | } else if (allowed == 0) { 232 | char err[2000]; 233 | snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio); 234 | PyErr_SetString(PyExc_ValueError, err); 235 | return NULL; 236 | } 237 | 238 | if (servo_set_range(key, range) == -1) { 239 | PyErr_SetString(PyExc_RuntimeError, "You must start() the Servo channel first"); 240 | return NULL; 241 | } 242 | 243 | Py_RETURN_NONE; 244 | } 245 | 246 | // python method SERVO.set_angle(channel, angle) 247 | static PyObject *py_set_angle(PyObject *self, PyObject *args, PyObject *kwargs) 248 | { 249 | int gpio; 250 | char key[8]; 251 | char *channel; 252 | float angle = 0.0; 253 | int allowed = -1; 254 | static char *kwlist[] = {"channel", "angle", NULL}; 255 | 256 | clear_error_msg(); 257 | 258 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &angle)) 259 | return NULL; 260 | 261 | //if (range > 360.0) { 262 | // PyErr_SetString(PyExc_ValueError, "range can not be greater than 360.0"); 263 | // return NULL; 264 | //} 265 | 266 | if (!get_key(channel, key)) { 267 | PyErr_SetString(PyExc_ValueError, "Invalid key or name."); 268 | return NULL; 269 | } 270 | 271 | // check to ensure gpio is one of the allowed pins 272 | // Not protecting the call as if the get_key() fails, we won't make it here 273 | get_gpio_number(channel, &gpio); 274 | if ((gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) { 275 | PyErr_SetString(PyExc_ValueError, "Servo currently not available on XIO-P0 to XIO-P7"); 276 | return NULL; 277 | } 278 | 279 | // Check to see if GPIO is allowed on the hardware 280 | // A 1 means we're good to go 281 | allowed = gpio_allowed(gpio); 282 | if (allowed == -1) { 283 | char err[2000]; 284 | snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg()); 285 | PyErr_SetString(PyExc_ValueError, err); 286 | return NULL; 287 | } else if (allowed == 0) { 288 | char err[2000]; 289 | snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio); 290 | PyErr_SetString(PyExc_ValueError, err); 291 | return NULL; 292 | } 293 | 294 | if (servo_set_angle(key, angle) == -1) { 295 | char err[2000]; 296 | snprintf(err, sizeof(err), "Error setting servo angle on pin %s (%s)", key, get_error_msg()); 297 | PyErr_SetString(PyExc_RuntimeError, err); 298 | return NULL; 299 | } 300 | 301 | Py_RETURN_NONE; 302 | } 303 | 304 | static const char moduledocstring[] = "Software Servo functionality of a CHIP using Python"; 305 | 306 | PyMethodDef servo_methods[] = { 307 | {"start", (PyCFunction)py_start_channel, METH_VARARGS | METH_KEYWORDS, "Set up and start the Servo. channel can be in the form of 'XIO-P0', or 'U14_13'"}, 308 | {"stop", (PyCFunction)py_stop_channel, METH_VARARGS | METH_KEYWORDS, "Stop the Servo. channel can be in the form of 'XIO-P0', or 'U14_13'"}, 309 | {"set_range", (PyCFunction)py_set_range, METH_VARARGS, "Change the servo range\nrange - max angular range of the servo" }, 310 | {"set_angle", (PyCFunction)py_set_angle, METH_VARARGS, "Change the servo angle\nangle - angle of the servo between +/-(range/2)" }, 311 | {"cleanup", (PyCFunction)py_cleanup, METH_VARARGS, "Clean up by resetting All or one Servo that have been used by this program."}, 312 | {"toggle_debug", py_toggle_debug, METH_VARARGS, "Toggles the enabling/disabling of Debug print output"}, 313 | {"is_chip_pro", py_is_chip_pro, METH_VARARGS, "Is hardware a CHIP Pro? Boolean False for normal CHIP/PocketCHIP (R8 SOC)"}, 314 | {NULL, NULL, 0, NULL} 315 | }; 316 | 317 | #if PY_MAJOR_VERSION > 2 318 | static struct PyModuleDef chipservomodule = { 319 | PyModuleDef_HEAD_INIT, 320 | "SERVO", // name of module 321 | moduledocstring, // module documentation, may be NULL 322 | -1, // size of per-interpreter state of the module, or -1 if the module keeps state in global variables. 323 | servo_methods 324 | }; 325 | #endif 326 | 327 | #if PY_MAJOR_VERSION > 2 328 | PyMODINIT_FUNC PyInit_SERVO(void) 329 | #else 330 | PyMODINIT_FUNC initSERVO(void) 331 | #endif 332 | { 333 | PyObject *module = NULL; 334 | 335 | #if PY_MAJOR_VERSION > 2 336 | if ((module = PyModule_Create(&chipservomodule)) == NULL) 337 | return NULL; 338 | #else 339 | if ((module = Py_InitModule3("SERVO", servo_methods, moduledocstring)) == NULL) 340 | return; 341 | #endif 342 | 343 | define_constants(module); 344 | 345 | 346 | #if PY_MAJOR_VERSION > 2 347 | return module; 348 | #else 349 | return; 350 | #endif 351 | } 352 | -------------------------------------------------------------------------------- /source/py_softpwm.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Brady Hurlburt 3 | 4 | Original BBIO Author Justin Cooper 5 | Modified for CHIP_IO Author Brady Hurlburt 6 | 7 | This file incorporates work covered by the following copyright and 8 | permission notice, all modified code adopts the original license: 9 | 10 | Copyright (c) 2013 Adafruit 11 | Author: Justin Cooper 12 | 13 | Permission is hereby granted, free of charge, to any person obtaining a copy of 14 | this software and associated documentation files (the "Software"), to deal in 15 | the Software without restriction, including without limitation the rights to 16 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 17 | of the Software, and to permit persons to whom the Software is furnished to do 18 | so, subject to the following conditions: 19 | 20 | The above copyright notice and this permission notice shall be included in all 21 | copies or substantial portions of the Software. 22 | 23 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 24 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 25 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 26 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 27 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 28 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 29 | SOFTWARE. 30 | */ 31 | 32 | #include "Python.h" 33 | #include "constants.h" 34 | #include "common.h" 35 | #include "c_softpwm.h" 36 | 37 | // python function toggle_debug() 38 | static PyObject *py_toggle_debug(PyObject *self, PyObject *args) 39 | { 40 | // toggle debug printing 41 | toggle_debug(); 42 | 43 | Py_RETURN_NONE; 44 | } 45 | 46 | // python function cleanup(channel) 47 | static PyObject *py_cleanup(PyObject *self, PyObject *args, PyObject *kwargs) 48 | { 49 | char key[8]; 50 | char *channel; 51 | static char *kwlist[] = {"channel", NULL}; 52 | 53 | clear_error_msg(); 54 | 55 | // Channel is optional 56 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|s", kwlist, &channel)) { 57 | return NULL; 58 | } 59 | 60 | // The !channel fixes issues #50 61 | if (channel == NULL || strcmp(channel, "\0") == 0) { 62 | softpwm_cleanup(); 63 | } else { 64 | if (!get_key(channel, key)) { 65 | softpwm_cleanup(); 66 | } 67 | softpwm_disable(key); 68 | } 69 | 70 | Py_RETURN_NONE; 71 | } 72 | 73 | static int init_module(void) 74 | { 75 | clear_error_msg(); 76 | 77 | // If we make it here, we're good to go 78 | if (DEBUG) 79 | printf(" ** init_module: setup complete **\n"); 80 | module_setup = 1; 81 | 82 | return 0; 83 | } 84 | 85 | // python function value = is_chip_pro() 86 | static PyObject *py_is_chip_pro(PyObject *self, PyObject *args) 87 | { 88 | PyObject *py_value; 89 | 90 | py_value = Py_BuildValue("i", is_this_chippro()); 91 | 92 | return py_value; 93 | } 94 | 95 | // python function start(channel, duty_cycle, freq, polarity) 96 | static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwargs) 97 | { 98 | char key[8]; 99 | char *channel = NULL; 100 | float frequency = 2000.0; 101 | float duty_cycle = 0.0; 102 | int polarity = 0; 103 | int gpio; 104 | int allowed = -1; 105 | static char *kwlist[] = {"channel", "duty_cycle", "frequency", "polarity", NULL}; 106 | 107 | clear_error_msg(); 108 | 109 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|ffi", kwlist, &channel, &duty_cycle, &frequency, &polarity)) { 110 | return NULL; 111 | } 112 | ASSRT(channel != NULL); 113 | 114 | if (!module_setup) { 115 | init_module(); 116 | } 117 | 118 | if (!get_key(channel, key)) { 119 | PyErr_SetString(PyExc_ValueError, "Invalid SOFTPWM key or name."); 120 | return NULL; 121 | } 122 | 123 | // check to ensure gpio is one of the allowed pins 124 | // Not protecting the call as if the get_key() fails, we won't make it here 125 | get_gpio_number(channel, &gpio); 126 | 127 | // Check to see if GPIO is allowed on the hardware 128 | // A 1 means we're good to go 129 | allowed = gpio_allowed(gpio); 130 | if (allowed == -1) { 131 | char err[2000]; 132 | snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg()); 133 | PyErr_SetString(PyExc_ValueError, err); 134 | return NULL; 135 | } else if (allowed == 0) { 136 | char err[2000]; 137 | snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio); 138 | PyErr_SetString(PyExc_ValueError, err); 139 | return NULL; 140 | } 141 | 142 | if (duty_cycle < 0.0 || duty_cycle > 100.0) { 143 | PyErr_SetString(PyExc_ValueError, "duty_cycle must have a value from 0.0 to 100.0"); 144 | return NULL; 145 | } 146 | 147 | if (frequency <= 0.0) { 148 | PyErr_SetString(PyExc_ValueError, "frequency must be greater than 0.0"); 149 | return NULL; 150 | } 151 | 152 | if (polarity < 0 || polarity > 1) { 153 | PyErr_SetString(PyExc_ValueError, "polarity must be either 0 or 1"); 154 | return NULL; 155 | } 156 | 157 | if (softpwm_start(key, duty_cycle, frequency, polarity) < 0) { 158 | printf("softpwm_start failed"); 159 | char err[2000]; 160 | snprintf(err, sizeof(err), "Error starting softpwm on pin %s (%s)", key, get_error_msg()); 161 | PyErr_SetString(PyExc_RuntimeError, err); 162 | return NULL; 163 | } 164 | 165 | Py_RETURN_NONE; 166 | } 167 | 168 | // python function stop(channel) 169 | static PyObject *py_stop_channel(PyObject *self, PyObject *args, PyObject *kwargs) 170 | { 171 | char key[8]; 172 | char *channel; 173 | int gpio; 174 | int allowed = -1; 175 | 176 | clear_error_msg(); 177 | 178 | if (!PyArg_ParseTuple(args, "s", &channel)) 179 | return NULL; 180 | 181 | if (!get_key(channel, key)) { 182 | PyErr_SetString(PyExc_ValueError, "Invalid PWM key or name."); 183 | return NULL; 184 | } 185 | 186 | // check to ensure gpio is one of the allowed pins 187 | // Not protecting the call as if the get_key() fails, we won't make it here 188 | get_gpio_number(channel, &gpio); 189 | 190 | // Check to see if GPIO is allowed on the hardware 191 | // A 1 means we're good to go 192 | allowed = gpio_allowed(gpio); 193 | if (allowed == -1) { 194 | char err[2000]; 195 | snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg()); 196 | PyErr_SetString(PyExc_ValueError, err); 197 | return NULL; 198 | } else if (allowed == 0) { 199 | char err[2000]; 200 | snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio); 201 | PyErr_SetString(PyExc_ValueError, err); 202 | return NULL; 203 | } 204 | 205 | softpwm_disable(key); 206 | 207 | Py_RETURN_NONE; 208 | } 209 | 210 | // python method PWM.set_duty_cycle(channel, duty_cycle) 211 | static PyObject *py_set_duty_cycle(PyObject *self, PyObject *args, PyObject *kwargs) 212 | { 213 | char key[8]; 214 | char *channel; 215 | int gpio; 216 | int allowed = -1; 217 | float duty_cycle = 0.0; 218 | static char *kwlist[] = {"channel", "duty_cycle", NULL}; 219 | 220 | clear_error_msg(); 221 | 222 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &duty_cycle)) 223 | return NULL; 224 | 225 | if (duty_cycle < 0.0 || duty_cycle > 100.0) { 226 | PyErr_SetString(PyExc_ValueError, "duty_cycle must have a value from 0.0 to 100.0"); 227 | return NULL; 228 | } 229 | 230 | if (!get_key(channel, key)) { 231 | PyErr_SetString(PyExc_ValueError, "Invalid PWM key or name."); 232 | return NULL; 233 | } 234 | 235 | // check to ensure gpio is one of the allowed pins 236 | // Not protecting the call as if the get_key() fails, we won't make it here 237 | get_gpio_number(channel, &gpio); 238 | 239 | // Check to see if GPIO is allowed on the hardware 240 | // A 1 means we're good to go 241 | allowed = gpio_allowed(gpio); 242 | if (allowed == -1) { 243 | char err[2000]; 244 | snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg()); 245 | PyErr_SetString(PyExc_ValueError, err); 246 | return NULL; 247 | } else if (allowed == 0) { 248 | char err[2000]; 249 | snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio); 250 | PyErr_SetString(PyExc_ValueError, err); 251 | return NULL; 252 | } 253 | 254 | if (softpwm_set_duty_cycle(key, duty_cycle) == -1) { 255 | PyErr_SetString(PyExc_RuntimeError, "You must start() the PWM channel first"); 256 | return NULL; 257 | } 258 | 259 | Py_RETURN_NONE; 260 | } 261 | 262 | // python method PWM.set_frequency(channel, frequency) 263 | static PyObject *py_set_frequency(PyObject *self, PyObject *args, PyObject *kwargs) 264 | { 265 | char key[8]; 266 | char *channel; 267 | int gpio; 268 | int allowed = -1; 269 | float frequency = 1.0; 270 | static char *kwlist[] = {"channel", "frequency", NULL}; 271 | 272 | clear_error_msg(); 273 | 274 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &frequency)) 275 | return NULL; 276 | 277 | if ((frequency <= 0.0) || (frequency > 10000.0)) { 278 | PyErr_SetString(PyExc_ValueError, "frequency must be greater than 0.0 and less than 10000.0"); 279 | return NULL; 280 | } 281 | 282 | if (!get_key(channel, key)) { 283 | PyErr_SetString(PyExc_ValueError, "Invalid PWM key or name."); 284 | return NULL; 285 | } 286 | 287 | // check to ensure gpio is one of the allowed pins 288 | // Not protecting the call as if the get_key() fails, we won't make it here 289 | get_gpio_number(channel, &gpio); 290 | 291 | // Check to see if GPIO is allowed on the hardware 292 | // A 1 means we're good to go 293 | allowed = gpio_allowed(gpio); 294 | if (allowed == -1) { 295 | char err[2000]; 296 | snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg()); 297 | PyErr_SetString(PyExc_ValueError, err); 298 | return NULL; 299 | } else if (allowed == 0) { 300 | char err[2000]; 301 | snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio); 302 | PyErr_SetString(PyExc_ValueError, err); 303 | return NULL; 304 | } 305 | 306 | if (softpwm_set_frequency(key, frequency) == -1) { 307 | PyErr_SetString(PyExc_RuntimeError, "You must start() the PWM channel first"); 308 | return NULL; 309 | } 310 | 311 | Py_RETURN_NONE; 312 | } 313 | 314 | static const char moduledocstring[] = "Software PWM functionality of a CHIP using Python"; 315 | 316 | PyMethodDef pwm_methods[] = { 317 | {"start", (PyCFunction)py_start_channel, METH_VARARGS | METH_KEYWORDS, "Set up and start the PWM channel. channel can be in the form of 'XIO-P0', or 'U14_13'"}, 318 | {"stop", (PyCFunction)py_stop_channel, METH_VARARGS | METH_KEYWORDS, "Stop the PWM channel. channel can be in the form of 'XIO-P0', or 'U14_13'"}, 319 | {"set_duty_cycle", (PyCFunction)py_set_duty_cycle, METH_VARARGS, "Change the duty cycle\ndutycycle - between 0.0 and 100.0" }, 320 | {"set_frequency", (PyCFunction)py_set_frequency, METH_VARARGS, "Change the frequency\nfrequency - frequency in Hz (freq > 0.0)" }, 321 | {"cleanup", (PyCFunction)py_cleanup, METH_VARARGS | METH_KEYWORDS, "Clean up by resetting all GPIO channels that have been used by this program to INPUT with no pullup/pulldown and no event detection"}, 322 | {"toggle_debug", py_toggle_debug, METH_VARARGS, "Toggles the enabling/disabling of Debug print output"}, 323 | {"is_chip_pro", py_is_chip_pro, METH_VARARGS, "Is hardware a CHIP Pro? Boolean False for normal CHIP/PocketCHIP (R8 SOC)"}, 324 | {NULL, NULL, 0, NULL} 325 | }; 326 | 327 | #if PY_MAJOR_VERSION > 2 328 | static struct PyModuleDef chipspwmmodule = { 329 | PyModuleDef_HEAD_INIT, 330 | "SOFTPWM", // name of module 331 | moduledocstring, // module documentation, may be NULL 332 | -1, // size of per-interpreter state of the module, or -1 if the module keeps state in global variables. 333 | pwm_methods 334 | }; 335 | #endif 336 | 337 | #if PY_MAJOR_VERSION > 2 338 | PyMODINIT_FUNC PyInit_SOFTPWM(void) 339 | #else 340 | PyMODINIT_FUNC initSOFTPWM(void) 341 | #endif 342 | { 343 | PyObject *module = NULL; 344 | 345 | #if PY_MAJOR_VERSION > 2 346 | if ((module = PyModule_Create(&chipspwmmodule)) == NULL) 347 | return NULL; 348 | #else 349 | if ((module = Py_InitModule3("SOFTPWM", pwm_methods, moduledocstring)) == NULL) 350 | return; 351 | #endif 352 | 353 | define_constants(module); 354 | 355 | 356 | #if PY_MAJOR_VERSION > 2 357 | return module; 358 | #else 359 | return; 360 | #endif 361 | } 362 | -------------------------------------------------------------------------------- /source/py_pwm.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Robert Wolterman 3 | 4 | Original BBIO Author Justin Cooper 5 | Modified for CHIP_IO Author Robert Wolterman 6 | 7 | This file incorporates work covered by the following copyright and 8 | permission notice, all modified code adopts the original license: 9 | 10 | Copyright (c) 2013 Adafruit 11 | Author: Justin Cooper 12 | 13 | Permission is hereby granted, free of charge, to any person obtaining a copy of 14 | this software and associated documentation files (the "Software"), to deal in 15 | the Software without restriction, including without limitation the rights to 16 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 17 | of the Software, and to permit persons to whom the Software is furnished to do 18 | so, subject to the following conditions: 19 | 20 | The above copyright notice and this permission notice shall be included in all 21 | copies or substantial portions of the Software. 22 | 23 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 24 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 25 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 26 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 27 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 28 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 29 | SOFTWARE. 30 | */ 31 | 32 | #include "Python.h" 33 | #include "constants.h" 34 | #include "common.h" 35 | #include "c_pwm.h" 36 | 37 | // python function cleanup(channel) 38 | static PyObject *py_cleanup(PyObject *self, PyObject *args, PyObject *kwargs) 39 | { 40 | char key[8]; 41 | char *channel; 42 | static char *kwlist[] = {"channel", NULL}; 43 | 44 | clear_error_msg(); 45 | 46 | // Channel is optional 47 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|s", kwlist, &channel)) { 48 | return NULL; 49 | } 50 | 51 | // The !channel fixes issues #50 52 | if (channel == NULL || strcmp(channel, "\0") == 0) { 53 | pwm_cleanup(); 54 | } else { 55 | if (!get_pwm_key(channel, key)) { 56 | pwm_cleanup(); 57 | } 58 | pwm_disable(key); 59 | } 60 | 61 | Py_RETURN_NONE; 62 | } 63 | 64 | // python function toggle_debug() 65 | static PyObject *py_toggle_debug(PyObject *self, PyObject *args) 66 | { 67 | // toggle debug printing 68 | toggle_debug(); 69 | 70 | Py_RETURN_NONE; 71 | } 72 | 73 | static int init_module(void) 74 | { 75 | clear_error_msg(); 76 | 77 | // If we make it here, we're good to go 78 | if (DEBUG) 79 | printf(" ** init_module: setup complete **\n"); 80 | module_setup = 1; 81 | 82 | return 0; 83 | } 84 | 85 | // python function value = is_chip_pro 86 | static PyObject *py_is_chip_pro(PyObject *self, PyObject *args) 87 | { 88 | PyObject *py_value; 89 | 90 | py_value = Py_BuildValue("i", is_this_chippro()); 91 | 92 | return py_value; 93 | } 94 | 95 | // python function start(channel, duty_cycle, freq) 96 | static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwargs) 97 | { 98 | char key[8]; 99 | char *channel; 100 | float frequency = 2000.0; 101 | float duty_cycle = 0.0; 102 | int polarity = 0; 103 | int allowed = -1; 104 | static char *kwlist[] = {"channel", "duty_cycle", "frequency", "polarity", NULL}; 105 | 106 | clear_error_msg(); 107 | 108 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|ffi", kwlist, &channel, &duty_cycle, &frequency, &polarity)) { 109 | return NULL; 110 | } 111 | 112 | if (!module_setup) { 113 | init_module(); 114 | } 115 | 116 | if (!get_pwm_key(channel, key)) { 117 | PyErr_SetString(PyExc_ValueError, "Invalid PWM key or name."); 118 | return NULL; 119 | } 120 | 121 | // Check to see if PWM is allowed on the hardware 122 | // A 1 means we're good to go 123 | allowed = pwm_allowed(key); 124 | if (allowed == -1) { 125 | char err[2000]; 126 | snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg()); 127 | PyErr_SetString(PyExc_ValueError, err); 128 | return NULL; 129 | } else if (allowed == 0) { 130 | char err[2000]; 131 | snprintf(err, sizeof(err), "PWM %s not available on current Hardware", key); 132 | PyErr_SetString(PyExc_ValueError, err); 133 | return NULL; 134 | } 135 | 136 | if (duty_cycle < 0.0 || duty_cycle > 100.0) { 137 | PyErr_SetString(PyExc_ValueError, "duty_cycle must have a value from 0.0 to 100.0"); 138 | return NULL; 139 | } 140 | 141 | if (frequency <= 0.0) { 142 | PyErr_SetString(PyExc_ValueError, "frequency must be greater than 0.0"); 143 | return NULL; 144 | } 145 | 146 | if (polarity < 0 || polarity > 1) { 147 | PyErr_SetString(PyExc_ValueError, "polarity must be either 0 or 1"); 148 | return NULL; 149 | } 150 | 151 | if (pwm_start(key, duty_cycle, frequency, polarity) < 0) { 152 | char err[2000]; 153 | snprintf(err, sizeof(err), "Unable to start PWM: %s (%s)", channel, get_error_msg()); 154 | PyErr_SetString(PyExc_ValueError, err); 155 | return NULL; 156 | } 157 | 158 | Py_RETURN_NONE; 159 | } 160 | 161 | // python function stop(channel) 162 | static PyObject *py_stop_channel(PyObject *self, PyObject *args, PyObject *kwargs) 163 | { 164 | char key[8]; 165 | char *channel; 166 | int allowed = -1; 167 | 168 | clear_error_msg(); 169 | 170 | if (!PyArg_ParseTuple(args, "s", &channel)) 171 | return NULL; 172 | 173 | if (!get_pwm_key(channel, key)) { 174 | PyErr_SetString(PyExc_ValueError, "Invalid PWM key or name."); 175 | return NULL; 176 | } 177 | 178 | // Check to see if PWM is allowed on the hardware 179 | // A 1 means we're good to go 180 | allowed = pwm_allowed(key); 181 | if (allowed == -1) { 182 | char err[2000]; 183 | snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg()); 184 | PyErr_SetString(PyExc_ValueError, err); 185 | return NULL; 186 | } else if (allowed == 0) { 187 | char err[2000]; 188 | snprintf(err, sizeof(err), "PWM %s not available on current Hardware", key); 189 | PyErr_SetString(PyExc_ValueError, err); 190 | return NULL; 191 | } 192 | 193 | if (pwm_disable(key) < 0) { 194 | char err[2000]; 195 | snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg()); 196 | PyErr_SetString(PyExc_ValueError, err); 197 | return NULL; 198 | } 199 | 200 | Py_RETURN_NONE; 201 | } 202 | 203 | // python method PWM.set_duty_cycle(channel, duty_cycle) 204 | static PyObject *py_set_duty_cycle(PyObject *self, PyObject *args, PyObject *kwargs) 205 | { 206 | char key[8]; 207 | char *channel; 208 | int allowed = -1; 209 | float duty_cycle = 0.0; 210 | static char *kwlist[] = {"channel", "duty_cycle", NULL}; 211 | 212 | clear_error_msg(); 213 | 214 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &duty_cycle)) 215 | return NULL; 216 | 217 | if (duty_cycle < 0.0 || duty_cycle > 100.0) { 218 | PyErr_SetString(PyExc_ValueError, "duty_cycle must have a value from 0.0 to 100.0"); 219 | return NULL; 220 | } 221 | 222 | if (!get_pwm_key(channel, key)) { 223 | PyErr_SetString(PyExc_ValueError, "Invalid PWM key or name."); 224 | return NULL; 225 | } 226 | 227 | // Check to see if PWM is allowed on the hardware 228 | // A 1 means we're good to go 229 | allowed = pwm_allowed(key); 230 | if (allowed == -1) { 231 | char err[2000]; 232 | snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg()); 233 | PyErr_SetString(PyExc_ValueError, err); 234 | return NULL; 235 | } else if (allowed == 0) { 236 | char err[2000]; 237 | snprintf(err, sizeof(err), "PWM %s not available on current Hardware", key); 238 | PyErr_SetString(PyExc_ValueError, err); 239 | return NULL; 240 | } 241 | 242 | if (pwm_set_duty_cycle(key, duty_cycle) == -1) { 243 | char err[2000]; 244 | snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg()); 245 | PyErr_SetString(PyExc_ValueError, err); 246 | return NULL; 247 | } 248 | 249 | Py_RETURN_NONE; 250 | } 251 | 252 | // python method PWM.set_pulse_width(channel, pulse_width_ns) 253 | static PyObject *py_set_pulse_width_ns(PyObject *self, PyObject *args, PyObject *kwargs) 254 | { 255 | char key[8]; 256 | char *channel; 257 | int allowed = -1; 258 | unsigned long pulse_width_ns = 0.0; 259 | unsigned long period_ns; 260 | static char *kwlist[] = {"channel", "pulse_width_ns", NULL}; 261 | 262 | clear_error_msg(); 263 | 264 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|k", kwlist, &channel, &pulse_width_ns)) 265 | return NULL; 266 | 267 | if (!get_pwm_key(channel, key)) { 268 | PyErr_SetString(PyExc_ValueError, "Invalid PWM key or name."); 269 | return NULL; 270 | } 271 | 272 | // Check to see if PWM is allowed on the hardware 273 | // A 1 means we're good to go 274 | allowed = pwm_allowed(key); 275 | if (allowed == -1) { 276 | char err[2000]; 277 | snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg()); 278 | PyErr_SetString(PyExc_ValueError, err); 279 | return NULL; 280 | } else if (allowed == 0) { 281 | char err[2000]; 282 | snprintf(err, sizeof(err), "PWM %s not available on current Hardware", key); 283 | PyErr_SetString(PyExc_ValueError, err); 284 | return NULL; 285 | } 286 | 287 | // Get the period out of the data struct 288 | int rtn = pwm_get_period_ns(key, &period_ns); 289 | if (rtn == -1) { 290 | PyErr_SetString(PyExc_ValueError, "period unable to be obtained"); 291 | return NULL; 292 | } 293 | 294 | if (pulse_width_ns < 0.0 || pulse_width_ns > period_ns) { 295 | PyErr_SetString(PyExc_ValueError, "pulse width must have a value from 0 to period"); 296 | return NULL; 297 | } 298 | 299 | if (pwm_set_pulse_width_ns(key, pulse_width_ns) < 0) { 300 | char err[2000]; 301 | snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg()); 302 | PyErr_SetString(PyExc_ValueError, err); 303 | return NULL; 304 | } 305 | 306 | Py_RETURN_NONE; 307 | } 308 | 309 | // python method PWM.set_frequency(channel, frequency) 310 | static PyObject *py_set_frequency(PyObject *self, PyObject *args, PyObject *kwargs) 311 | { 312 | char key[8]; 313 | char *channel; 314 | int allowed = -1; 315 | float frequency = 1.0; 316 | static char *kwlist[] = {"channel", "frequency", NULL}; 317 | 318 | clear_error_msg(); 319 | 320 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &frequency)) 321 | return NULL; 322 | 323 | if (frequency <= 0.0) { 324 | PyErr_SetString(PyExc_ValueError, "frequency must be greater than 0.0"); 325 | return NULL; 326 | } 327 | 328 | if (!get_pwm_key(channel, key)) { 329 | PyErr_SetString(PyExc_ValueError, "Invalid PWM key or name."); 330 | return NULL; 331 | } 332 | 333 | // Check to see if PWM is allowed on the hardware 334 | // A 1 means we're good to go 335 | allowed = pwm_allowed(key); 336 | if (allowed == -1) { 337 | char err[2000]; 338 | snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg()); 339 | PyErr_SetString(PyExc_ValueError, err); 340 | return NULL; 341 | } else if (allowed == 0) { 342 | char err[2000]; 343 | snprintf(err, sizeof(err), "PWM %s not available on current Hardware", key); 344 | PyErr_SetString(PyExc_ValueError, err); 345 | return NULL; 346 | } 347 | 348 | if (pwm_set_frequency(key, frequency) < 0) { 349 | char err[2000]; 350 | snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg()); 351 | PyErr_SetString(PyExc_ValueError, err); 352 | return NULL; 353 | } 354 | 355 | Py_RETURN_NONE; 356 | } 357 | 358 | // python method PWM.set_period_ns(channel, period_ns) 359 | static PyObject *py_set_period_ns(PyObject *self, PyObject *args, PyObject *kwargs) 360 | { 361 | char key[8]; 362 | char *channel; 363 | int allowed = -1; 364 | unsigned long period_ns = 2e6; 365 | static char *kwlist[] = {"channel", "period_ns", NULL}; 366 | 367 | clear_error_msg(); 368 | 369 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|k", kwlist, &channel, &period_ns)) 370 | return NULL; 371 | 372 | if (period_ns <= 0) { 373 | PyErr_SetString(PyExc_ValueError, "period must be greater than 0ns"); 374 | return NULL; 375 | } 376 | 377 | if (!get_pwm_key(channel, key)) { 378 | PyErr_SetString(PyExc_ValueError, "Invalid PWM key or name."); 379 | return NULL; 380 | } 381 | 382 | // Check to see if PWM is allowed on the hardware 383 | // A 1 means we're good to go 384 | allowed = pwm_allowed(key); 385 | if (allowed == -1) { 386 | char err[2000]; 387 | snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg()); 388 | PyErr_SetString(PyExc_ValueError, err); 389 | return NULL; 390 | } else if (allowed == 0) { 391 | char err[2000]; 392 | snprintf(err, sizeof(err), "PWM %s not available on current Hardware", key); 393 | PyErr_SetString(PyExc_ValueError, err); 394 | return NULL; 395 | } 396 | 397 | if (pwm_set_period_ns(key, period_ns) < 0) { 398 | char err[2000]; 399 | snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg()); 400 | PyErr_SetString(PyExc_ValueError, err); 401 | return NULL; 402 | } 403 | 404 | Py_RETURN_NONE; 405 | } 406 | 407 | static const char moduledocstring[] = "Hardware PWM functionality of a CHIP using Python"; 408 | 409 | PyMethodDef pwm_methods[] = { 410 | {"start", (PyCFunction)py_start_channel, METH_VARARGS | METH_KEYWORDS, "Set up and start the PWM channel. channel can be in the form of 'PWM0', or 'U13_18'"}, 411 | {"stop", (PyCFunction)py_stop_channel, METH_VARARGS | METH_KEYWORDS, "Stop the PWM channel. channel can be in the form of 'PWM0', or 'U13_18'"}, 412 | {"set_duty_cycle", (PyCFunction)py_set_duty_cycle, METH_VARARGS, "Change the duty cycle\ndutycycle - between 0.0 and 100.0" }, 413 | {"set_frequency", (PyCFunction)py_set_frequency, METH_VARARGS, "Change the frequency\nfrequency - frequency in Hz (freq > 0.0)" }, 414 | {"set_period_ns", (PyCFunction)py_set_period_ns, METH_VARARGS, "Change the period\nperiod_ns - period in nanoseconds" }, 415 | {"set_pulse_width_ns", (PyCFunction)py_set_pulse_width_ns, METH_VARARGS, "Change the period\npulse_width_ns - pulse width in nanoseconds" }, 416 | {"cleanup", (PyCFunction)py_cleanup, METH_VARARGS | METH_KEYWORDS, "Clean up by resetting PWM channel(s) that have been used by this program to be disabled"}, 417 | {"toggle_debug", py_toggle_debug, METH_VARARGS, "Toggles the enabling/disabling of Debug print output"}, 418 | {"is_chip_pro", py_is_chip_pro, METH_VARARGS, "Is hardware a CHIP Pro? Boolean False for normal CHIP/PocketCHIP (R8 SOC)"}, 419 | {NULL, NULL, 0, NULL} 420 | }; 421 | 422 | #if PY_MAJOR_VERSION > 2 423 | static struct PyModuleDef chippwmmodule = { 424 | PyModuleDef_HEAD_INIT, 425 | "PWM", // name of module 426 | moduledocstring, // module documentation, may be NULL 427 | -1, // size of per-interpreter state of the module, or -1 if the module keeps state in global variables. 428 | pwm_methods 429 | }; 430 | #endif 431 | 432 | #if PY_MAJOR_VERSION > 2 433 | PyMODINIT_FUNC PyInit_PWM(void) 434 | #else 435 | PyMODINIT_FUNC initPWM(void) 436 | #endif 437 | { 438 | PyObject *module = NULL; 439 | 440 | #if PY_MAJOR_VERSION > 2 441 | if ((module = PyModule_Create(&chippwmmodule)) == NULL) 442 | return NULL; 443 | #else 444 | if ((module = Py_InitModule3("PWM", pwm_methods, moduledocstring)) == NULL) 445 | return; 446 | #endif 447 | 448 | define_constants(module); 449 | 450 | 451 | #if PY_MAJOR_VERSION > 2 452 | return module; 453 | #else 454 | return; 455 | #endif 456 | } 457 | -------------------------------------------------------------------------------- /distribute_setup.py: -------------------------------------------------------------------------------- 1 | #!python 2 | """Bootstrap distribute installation 3 | 4 | If you want to use setuptools in your package's setup.py, just include this 5 | file in the same directory with it, and add this to the top of your setup.py:: 6 | 7 | from distribute_setup import use_setuptools 8 | use_setuptools() 9 | 10 | If you want to require a specific version of setuptools, set a download 11 | mirror, or use an alternate download directory, you can do so by supplying 12 | the appropriate options to ``use_setuptools()``. 13 | 14 | This file can also be run as a script to install or upgrade setuptools. 15 | """ 16 | import os 17 | import shutil 18 | import sys 19 | import time 20 | import fnmatch 21 | import tempfile 22 | import tarfile 23 | import optparse 24 | 25 | from distutils import log 26 | 27 | try: 28 | from site import USER_SITE 29 | except ImportError: 30 | USER_SITE = None 31 | 32 | try: 33 | import subprocess 34 | 35 | def _python_cmd(*args): 36 | args = (sys.executable,) + args 37 | return subprocess.call(args) == 0 38 | 39 | except ImportError: 40 | # will be used for python 2.3 41 | def _python_cmd(*args): 42 | args = (sys.executable,) + args 43 | # quoting arguments if windows 44 | if sys.platform == 'win32': 45 | def quote(arg): 46 | if ' ' in arg: 47 | return '"%s"' % arg 48 | return arg 49 | args = [quote(arg) for arg in args] 50 | return os.spawnl(os.P_WAIT, sys.executable, *args) == 0 51 | 52 | DEFAULT_VERSION = "0.0.1" 53 | DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/" 54 | SETUPTOOLS_FAKED_VERSION = "0.6c11" 55 | 56 | SETUPTOOLS_PKG_INFO = """\ 57 | Metadata-Version: 1.0 58 | Name: setuptools 59 | Version: %s 60 | Summary: xxxx 61 | Home-page: xxx 62 | Author: xxx 63 | Author-email: xxx 64 | License: xxx 65 | Description: xxx 66 | """ % SETUPTOOLS_FAKED_VERSION 67 | 68 | 69 | def _install(tarball, install_args=()): 70 | # extracting the tarball 71 | tmpdir = tempfile.mkdtemp() 72 | log.warn('Extracting in %s', tmpdir) 73 | old_wd = os.getcwd() 74 | try: 75 | os.chdir(tmpdir) 76 | tar = tarfile.open(tarball) 77 | _extractall(tar) 78 | tar.close() 79 | 80 | # going in the directory 81 | subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) 82 | os.chdir(subdir) 83 | log.warn('Now working in %s', subdir) 84 | 85 | # installing 86 | log.warn('Installing Distribute') 87 | if not _python_cmd('setup.py', 'install', *install_args): 88 | log.warn('Something went wrong during the installation.') 89 | log.warn('See the error message above.') 90 | # exitcode will be 2 91 | return 2 92 | finally: 93 | os.chdir(old_wd) 94 | shutil.rmtree(tmpdir) 95 | 96 | 97 | def _build_egg(egg, tarball, to_dir): 98 | # extracting the tarball 99 | tmpdir = tempfile.mkdtemp() 100 | log.warn('Extracting in %s', tmpdir) 101 | old_wd = os.getcwd() 102 | try: 103 | os.chdir(tmpdir) 104 | tar = tarfile.open(tarball) 105 | _extractall(tar) 106 | tar.close() 107 | 108 | # going in the directory 109 | subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) 110 | os.chdir(subdir) 111 | log.warn('Now working in %s', subdir) 112 | 113 | # building an egg 114 | log.warn('Building a Distribute egg in %s', to_dir) 115 | _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) 116 | 117 | finally: 118 | os.chdir(old_wd) 119 | shutil.rmtree(tmpdir) 120 | # returning the result 121 | log.warn(egg) 122 | if not os.path.exists(egg): 123 | raise IOError('Could not build the egg.') 124 | 125 | 126 | def _do_download(version, download_base, to_dir, download_delay): 127 | egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg' 128 | % (version, sys.version_info[0], sys.version_info[1])) 129 | if not os.path.exists(egg): 130 | tarball = download_setuptools(version, download_base, 131 | to_dir, download_delay) 132 | _build_egg(egg, tarball, to_dir) 133 | sys.path.insert(0, egg) 134 | import setuptools 135 | setuptools.bootstrap_install_from = egg 136 | 137 | 138 | def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, 139 | to_dir=os.curdir, download_delay=15, no_fake=True): 140 | # making sure we use the absolute path 141 | to_dir = os.path.abspath(to_dir) 142 | was_imported = 'pkg_resources' in sys.modules or \ 143 | 'setuptools' in sys.modules 144 | try: 145 | try: 146 | import pkg_resources 147 | 148 | # Setuptools 0.7b and later is a suitable (and preferable) 149 | # substitute for any Distribute version. 150 | try: 151 | pkg_resources.require("setuptools>=0.7b") 152 | return 153 | except (pkg_resources.DistributionNotFound, 154 | pkg_resources.VersionConflict): 155 | pass 156 | 157 | if not hasattr(pkg_resources, '_distribute'): 158 | if not no_fake: 159 | _fake_setuptools() 160 | raise ImportError 161 | except ImportError: 162 | return _do_download(version, download_base, to_dir, download_delay) 163 | try: 164 | pkg_resources.require("distribute>=" + version) 165 | return 166 | except pkg_resources.VersionConflict: 167 | e = sys.exc_info()[1] 168 | if was_imported: 169 | sys.stderr.write( 170 | "The required version of distribute (>=%s) is not available,\n" 171 | "and can't be installed while this script is running. Please\n" 172 | "install a more recent version first, using\n" 173 | "'easy_install -U distribute'." 174 | "\n\n(Currently using %r)\n" % (version, e.args[0])) 175 | sys.exit(2) 176 | else: 177 | del pkg_resources, sys.modules['pkg_resources'] # reload ok 178 | return _do_download(version, download_base, to_dir, 179 | download_delay) 180 | except pkg_resources.DistributionNotFound: 181 | return _do_download(version, download_base, to_dir, 182 | download_delay) 183 | finally: 184 | if not no_fake: 185 | _create_fake_setuptools_pkg_info(to_dir) 186 | 187 | 188 | def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, 189 | to_dir=os.curdir, delay=15): 190 | """Download distribute from a specified location and return its filename 191 | 192 | `version` should be a valid distribute version number that is available 193 | as an egg for download under the `download_base` URL (which should end 194 | with a '/'). `to_dir` is the directory where the egg will be downloaded. 195 | `delay` is the number of seconds to pause before an actual download 196 | attempt. 197 | """ 198 | # making sure we use the absolute path 199 | to_dir = os.path.abspath(to_dir) 200 | try: 201 | from urllib.request import urlopen 202 | except ImportError: 203 | from urllib2 import urlopen 204 | tgz_name = "distribute-%s.tar.gz" % version 205 | url = download_base + tgz_name 206 | saveto = os.path.join(to_dir, tgz_name) 207 | src = dst = None 208 | if not os.path.exists(saveto): # Avoid repeated downloads 209 | try: 210 | log.warn("Downloading %s", url) 211 | src = urlopen(url) 212 | # Read/write all in one block, so we don't create a corrupt file 213 | # if the download is interrupted. 214 | data = src.read() 215 | dst = open(saveto, "wb") 216 | dst.write(data) 217 | finally: 218 | if src: 219 | src.close() 220 | if dst: 221 | dst.close() 222 | return os.path.realpath(saveto) 223 | 224 | 225 | def _no_sandbox(function): 226 | def __no_sandbox(*args, **kw): 227 | try: 228 | from setuptools.sandbox import DirectorySandbox 229 | if not hasattr(DirectorySandbox, '_old'): 230 | def violation(*args): 231 | pass 232 | DirectorySandbox._old = DirectorySandbox._violation 233 | DirectorySandbox._violation = violation 234 | patched = True 235 | else: 236 | patched = False 237 | except ImportError: 238 | patched = False 239 | 240 | try: 241 | return function(*args, **kw) 242 | finally: 243 | if patched: 244 | DirectorySandbox._violation = DirectorySandbox._old 245 | del DirectorySandbox._old 246 | 247 | return __no_sandbox 248 | 249 | 250 | def _patch_file(path, content): 251 | """Will backup the file then patch it""" 252 | f = open(path) 253 | existing_content = f.read() 254 | f.close() 255 | if existing_content == content: 256 | # already patched 257 | log.warn('Already patched.') 258 | return False 259 | log.warn('Patching...') 260 | _rename_path(path) 261 | f = open(path, 'w') 262 | try: 263 | f.write(content) 264 | finally: 265 | f.close() 266 | return True 267 | 268 | _patch_file = _no_sandbox(_patch_file) 269 | 270 | 271 | def _same_content(path, content): 272 | f = open(path) 273 | existing_content = f.read() 274 | f.close() 275 | return existing_content == content 276 | 277 | 278 | def _rename_path(path): 279 | new_name = path + '.OLD.%s' % time.time() 280 | log.warn('Renaming %s to %s', path, new_name) 281 | os.rename(path, new_name) 282 | return new_name 283 | 284 | 285 | def _remove_flat_installation(placeholder): 286 | if not os.path.isdir(placeholder): 287 | log.warn('Unkown installation at %s', placeholder) 288 | return False 289 | found = False 290 | for file in os.listdir(placeholder): 291 | if fnmatch.fnmatch(file, 'setuptools*.egg-info'): 292 | found = True 293 | break 294 | if not found: 295 | log.warn('Could not locate setuptools*.egg-info') 296 | return 297 | 298 | log.warn('Moving elements out of the way...') 299 | pkg_info = os.path.join(placeholder, file) 300 | if os.path.isdir(pkg_info): 301 | patched = _patch_egg_dir(pkg_info) 302 | else: 303 | patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO) 304 | 305 | if not patched: 306 | log.warn('%s already patched.', pkg_info) 307 | return False 308 | # now let's move the files out of the way 309 | for element in ('setuptools', 'pkg_resources.py', 'site.py'): 310 | element = os.path.join(placeholder, element) 311 | if os.path.exists(element): 312 | _rename_path(element) 313 | else: 314 | log.warn('Could not find the %s element of the ' 315 | 'Setuptools distribution', element) 316 | return True 317 | 318 | _remove_flat_installation = _no_sandbox(_remove_flat_installation) 319 | 320 | 321 | def _after_install(dist): 322 | log.warn('After install bootstrap.') 323 | placeholder = dist.get_command_obj('install').install_purelib 324 | _create_fake_setuptools_pkg_info(placeholder) 325 | 326 | 327 | def _create_fake_setuptools_pkg_info(placeholder): 328 | if not placeholder or not os.path.exists(placeholder): 329 | log.warn('Could not find the install location') 330 | return 331 | pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1]) 332 | setuptools_file = 'setuptools-%s-py%s.egg-info' % \ 333 | (SETUPTOOLS_FAKED_VERSION, pyver) 334 | pkg_info = os.path.join(placeholder, setuptools_file) 335 | if os.path.exists(pkg_info): 336 | log.warn('%s already exists', pkg_info) 337 | return 338 | 339 | log.warn('Creating %s', pkg_info) 340 | try: 341 | f = open(pkg_info, 'w') 342 | except EnvironmentError: 343 | log.warn("Don't have permissions to write %s, skipping", pkg_info) 344 | return 345 | try: 346 | f.write(SETUPTOOLS_PKG_INFO) 347 | finally: 348 | f.close() 349 | 350 | pth_file = os.path.join(placeholder, 'setuptools.pth') 351 | log.warn('Creating %s', pth_file) 352 | f = open(pth_file, 'w') 353 | try: 354 | f.write(os.path.join(os.curdir, setuptools_file)) 355 | finally: 356 | f.close() 357 | 358 | _create_fake_setuptools_pkg_info = _no_sandbox( 359 | _create_fake_setuptools_pkg_info 360 | ) 361 | 362 | 363 | def _patch_egg_dir(path): 364 | # let's check if it's already patched 365 | pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO') 366 | if os.path.exists(pkg_info): 367 | if _same_content(pkg_info, SETUPTOOLS_PKG_INFO): 368 | log.warn('%s already patched.', pkg_info) 369 | return False 370 | _rename_path(path) 371 | os.mkdir(path) 372 | os.mkdir(os.path.join(path, 'EGG-INFO')) 373 | pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO') 374 | f = open(pkg_info, 'w') 375 | try: 376 | f.write(SETUPTOOLS_PKG_INFO) 377 | finally: 378 | f.close() 379 | return True 380 | 381 | _patch_egg_dir = _no_sandbox(_patch_egg_dir) 382 | 383 | 384 | def _before_install(): 385 | log.warn('Before install bootstrap.') 386 | _fake_setuptools() 387 | 388 | 389 | def _under_prefix(location): 390 | if 'install' not in sys.argv: 391 | return True 392 | args = sys.argv[sys.argv.index('install') + 1:] 393 | for index, arg in enumerate(args): 394 | for option in ('--root', '--prefix'): 395 | if arg.startswith('%s=' % option): 396 | top_dir = arg.split('root=')[-1] 397 | return location.startswith(top_dir) 398 | elif arg == option: 399 | if len(args) > index: 400 | top_dir = args[index + 1] 401 | return location.startswith(top_dir) 402 | if arg == '--user' and USER_SITE is not None: 403 | return location.startswith(USER_SITE) 404 | return True 405 | 406 | 407 | def _fake_setuptools(): 408 | log.warn('Scanning installed packages') 409 | try: 410 | import pkg_resources 411 | except ImportError: 412 | # we're cool 413 | log.warn('Setuptools or Distribute does not seem to be installed.') 414 | return 415 | ws = pkg_resources.working_set 416 | try: 417 | setuptools_dist = ws.find( 418 | pkg_resources.Requirement.parse('setuptools', replacement=False) 419 | ) 420 | except TypeError: 421 | # old distribute API 422 | setuptools_dist = ws.find( 423 | pkg_resources.Requirement.parse('setuptools') 424 | ) 425 | 426 | if setuptools_dist is None: 427 | log.warn('No setuptools distribution found') 428 | return 429 | # detecting if it was already faked 430 | setuptools_location = setuptools_dist.location 431 | log.warn('Setuptools installation detected at %s', setuptools_location) 432 | 433 | # if --root or --preix was provided, and if 434 | # setuptools is not located in them, we don't patch it 435 | if not _under_prefix(setuptools_location): 436 | log.warn('Not patching, --root or --prefix is installing Distribute' 437 | ' in another location') 438 | return 439 | 440 | # let's see if its an egg 441 | if not setuptools_location.endswith('.egg'): 442 | log.warn('Non-egg installation') 443 | res = _remove_flat_installation(setuptools_location) 444 | if not res: 445 | return 446 | else: 447 | log.warn('Egg installation') 448 | pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO') 449 | if (os.path.exists(pkg_info) and 450 | _same_content(pkg_info, SETUPTOOLS_PKG_INFO)): 451 | log.warn('Already patched.') 452 | return 453 | log.warn('Patching...') 454 | # let's create a fake egg replacing setuptools one 455 | res = _patch_egg_dir(setuptools_location) 456 | if not res: 457 | return 458 | log.warn('Patching complete.') 459 | _relaunch() 460 | 461 | 462 | def _relaunch(): 463 | log.warn('Relaunching...') 464 | # we have to relaunch the process 465 | # pip marker to avoid a relaunch bug 466 | _cmd1 = ['-c', 'install', '--single-version-externally-managed'] 467 | _cmd2 = ['-c', 'install', '--record'] 468 | if sys.argv[:3] == _cmd1 or sys.argv[:3] == _cmd2: 469 | sys.argv[0] = 'setup.py' 470 | args = [sys.executable] + sys.argv 471 | sys.exit(subprocess.call(args)) 472 | 473 | 474 | def _extractall(self, path=".", members=None): 475 | """Extract all members from the archive to the current working 476 | directory and set owner, modification time and permissions on 477 | directories afterwards. `path' specifies a different directory 478 | to extract to. `members' is optional and must be a subset of the 479 | list returned by getmembers(). 480 | """ 481 | import copy 482 | import operator 483 | from tarfile import ExtractError 484 | directories = [] 485 | 486 | if members is None: 487 | members = self 488 | 489 | for tarinfo in members: 490 | if tarinfo.isdir(): 491 | # Extract directories with a safe mode. 492 | directories.append(tarinfo) 493 | tarinfo = copy.copy(tarinfo) 494 | tarinfo.mode = 448 # decimal for oct 0700 495 | self.extract(tarinfo, path) 496 | 497 | # Reverse sort directories. 498 | if sys.version_info < (2, 4): 499 | def sorter(dir1, dir2): 500 | return cmp(dir1.name, dir2.name) 501 | directories.sort(sorter) 502 | directories.reverse() 503 | else: 504 | directories.sort(key=operator.attrgetter('name'), reverse=True) 505 | 506 | # Set correct owner, mtime and filemode on directories. 507 | for tarinfo in directories: 508 | dirpath = os.path.join(path, tarinfo.name) 509 | try: 510 | self.chown(tarinfo, dirpath) 511 | self.utime(tarinfo, dirpath) 512 | self.chmod(tarinfo, dirpath) 513 | except ExtractError: 514 | e = sys.exc_info()[1] 515 | if self.errorlevel > 1: 516 | raise 517 | else: 518 | self._dbg(1, "tarfile: %s" % e) 519 | 520 | 521 | def _build_install_args(options): 522 | """ 523 | Build the arguments to 'python setup.py install' on the distribute package 524 | """ 525 | install_args = [] 526 | if options.user_install: 527 | if sys.version_info < (2, 6): 528 | log.warn("--user requires Python 2.6 or later") 529 | raise SystemExit(1) 530 | install_args.append('--user') 531 | return install_args 532 | 533 | def _parse_args(): 534 | """ 535 | Parse the command line for options 536 | """ 537 | parser = optparse.OptionParser() 538 | parser.add_option( 539 | '--user', dest='user_install', action='store_true', default=False, 540 | help='install in user site package (requires Python 2.6 or later)') 541 | parser.add_option( 542 | '--download-base', dest='download_base', metavar="URL", 543 | default=DEFAULT_URL, 544 | help='alternative URL from where to download the distribute package') 545 | options, args = parser.parse_args() 546 | # positional arguments are ignored 547 | return options 548 | 549 | def main(version=DEFAULT_VERSION): 550 | """Install or upgrade setuptools and EasyInstall""" 551 | options = _parse_args() 552 | tarball = download_setuptools(download_base=options.download_base) 553 | return _install(tarball, _build_install_args(options)) 554 | 555 | if __name__ == '__main__': 556 | sys.exit(main()) 557 | --------------------------------------------------------------------------------