diff options
author | Cody Hiar <codyfh@gmail.com> | 2018-05-16 21:14:38 -0600 |
---|---|---|
committer | Cody Hiar <codyfh@gmail.com> | 2018-05-16 21:14:38 -0600 |
commit | 611a8b7be4331e4f8416c4d10a0be47a109b47e4 (patch) | |
tree | 206adb073b1eeda504f05e9a81eabc416da961aa /Adafruit_Python_MCP3008 | |
parent | cec86d65a5b80bcfaf447ff078031d92ed3c7557 (diff) |
Adding MCP3008 library
Diffstat (limited to 'Adafruit_Python_MCP3008')
-rw-r--r-- | Adafruit_Python_MCP3008/.github/ISSUE_TEMPLATE.md | 47 | ||||
-rw-r--r-- | Adafruit_Python_MCP3008/.github/PULL_REQUEST_TEMPLATE.md | 26 | ||||
-rw-r--r-- | Adafruit_Python_MCP3008/.gitignore | 63 | ||||
-rw-r--r-- | Adafruit_Python_MCP3008/Adafruit_MCP3008/MCP3008.py | 92 | ||||
-rw-r--r-- | Adafruit_Python_MCP3008/Adafruit_MCP3008/__init__.py | 1 | ||||
-rw-r--r-- | Adafruit_Python_MCP3008/LICENSE | 21 | ||||
-rw-r--r-- | Adafruit_Python_MCP3008/README.md | 19 | ||||
-rw-r--r-- | Adafruit_Python_MCP3008/examples/differential.py | 38 | ||||
-rw-r--r-- | Adafruit_Python_MCP3008/examples/simpletest.py | 39 | ||||
-rw-r--r-- | Adafruit_Python_MCP3008/ez_setup.py | 332 | ||||
-rw-r--r-- | Adafruit_Python_MCP3008/setup.py | 30 |
11 files changed, 708 insertions, 0 deletions
diff --git a/Adafruit_Python_MCP3008/.github/ISSUE_TEMPLATE.md b/Adafruit_Python_MCP3008/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..6344b2f --- /dev/null +++ b/Adafruit_Python_MCP3008/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,47 @@ +Thank you for opening an issue on an Adafruit Python library repository. To +improve the speed of resolution please review the following guidelines and +common troubleshooting steps below before creating the issue: + +- **Do not use GitHub issues for troubleshooting projects and issues.** Instead use + the forums at http://forums.adafruit.com to ask questions and troubleshoot why + something isn't working as expected. In many cases the problem is a common issue + that you will more quickly receive help from the forum community. GitHub issues + are meant for known defects in the code. If you don't know if there is a defect + in the code then start with troubleshooting on the forum first. + +- **If following a tutorial or guide be sure you didn't miss a step.** Carefully + check all of the steps and commands to run have been followed. Consult the + forum if you're unsure or have questions about steps in a guide/tutorial. + +- **For Python/Raspberry Pi projects check these very common issues to ensure they don't apply**: + + - If you are receiving an **ImportError: No module named...** error then a + library the code depends on is not installed. Check the tutorial/guide or + README to ensure you have installed the necessary libraries. Usually the + missing library can be installed with the `pip` tool, but check the tutorial/guide + for the exact command. + + - **Be sure you are supplying adequate power to the board.** Check the specs of + your board and power in an external power supply. In many cases just + plugging a board into your computer is not enough to power it and other + peripherals. + + - **Double check all soldering joints and connections.** Flakey connections + cause many mysterious problems. See the [guide to excellent soldering](https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools) for examples of good solder joints. + +If you're sure this issue is a defect in the code and checked the steps above +please fill in the following fields to provide enough troubleshooting information. +You may delete the guideline and text above to just leave the following details: + +- Platform/operating system (i.e. Raspberry Pi with Raspbian operating system, + Windows 32-bit, Windows 64-bit, Mac OSX 64-bit, etc.): **INSERT PLATFORM/OPERATING + SYSTEM HERE** + +- Python version (run `python -version` or `python3 -version`): **INSERT PYTHON + VERSION HERE** + +- Error message you are receiving, including any Python exception traces: **INSERT + ERROR MESAGE/EXCEPTION TRACES HERE*** + +- List the steps to reproduce the problem below (if possible attach code or commands + to run): **LIST REPRO STEPS BELOW** diff --git a/Adafruit_Python_MCP3008/.github/PULL_REQUEST_TEMPLATE.md b/Adafruit_Python_MCP3008/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..7b641eb --- /dev/null +++ b/Adafruit_Python_MCP3008/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,26 @@ +Thank you for creating a pull request to contribute to Adafruit's GitHub code! +Before you open the request please review the following guidelines and tips to +help it be more easily integrated: + +- **Describe the scope of your change--i.e. what the change does and what parts + of the code were modified.** This will help us understand any risks of integrating + the code. + +- **Describe any known limitations with your change.** For example if the change + doesn't apply to a supported platform of the library please mention it. + +- **Please run any tests or examples that can exercise your modified code.** We + strive to not break users of the code and running tests/examples helps with this + process. + +Thank you again for contributing! We will try to test and integrate the change +as soon as we can, but be aware we have many GitHub repositories to manage and +can't immediately respond to every request. There is no need to bump or check in +on a pull request (it will clutter the discussion of the request). + +Also don't be worried if the request is closed or not integrated--sometimes the +priorities of Adafruit's GitHub code (education, ease of use) might not match the +priorities of the pull request. Don't fret, the open source community thrives on +forks and GitHub makes it easy to keep your changes in a forked repo. + +After reviewing the guidelines above you can delete this text from the pull request. diff --git a/Adafruit_Python_MCP3008/.gitignore b/Adafruit_Python_MCP3008/.gitignore new file mode 100644 index 0000000..e2160db --- /dev/null +++ b/Adafruit_Python_MCP3008/.gitignore @@ -0,0 +1,63 @@ +setuptools-* +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints diff --git a/Adafruit_Python_MCP3008/Adafruit_MCP3008/MCP3008.py b/Adafruit_Python_MCP3008/Adafruit_MCP3008/MCP3008.py new file mode 100644 index 0000000..027cec7 --- /dev/null +++ b/Adafruit_Python_MCP3008/Adafruit_MCP3008/MCP3008.py @@ -0,0 +1,92 @@ +# Copyright (c) 2016 Adafruit Industries +# Author: Tony DiCola +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +import Adafruit_GPIO as GPIO +import Adafruit_GPIO.SPI as SPI + + +class MCP3008(object): + """Class to represent an Adafruit MCP3008 analog to digital converter. + """ + + def __init__(self, clk=None, cs=None, miso=None, mosi=None, spi=None, gpio=None): + """Initialize MAX31855 device with software SPI on the specified CLK, + CS, and DO pins. Alternatively can specify hardware SPI by sending an + Adafruit_GPIO.SPI.SpiDev device in the spi parameter. + """ + self._spi = None + # Handle hardware SPI + if spi is not None: + self._spi = spi + elif clk is not None and cs is not None and miso is not None and mosi is not None: + # Default to platform GPIO if not provided. + if gpio is None: + gpio = GPIO.get_platform_gpio() + self._spi = SPI.BitBang(gpio, clk, mosi, miso, cs) + else: + raise ValueError('Must specify either spi for for hardware SPI or clk, cs, miso, and mosi for softwrare SPI!') + self._spi.set_clock_hz(1000000) + self._spi.set_mode(0) + self._spi.set_bit_order(SPI.MSBFIRST) + + def read_adc(self, adc_number): + """Read the current value of the specified ADC channel (0-7). The values + can range from 0 to 1023 (10-bits). + """ + assert 0 <= adc_number <= 7, 'ADC number must be a value of 0-7!' + # Build a single channel read command. + # For example channel zero = 0b11000000 + command = 0b11 << 6 # Start bit, single channel read + command |= (adc_number & 0x07) << 3 # Channel number (in 3 bits) + # Note the bottom 3 bits of command are 0, this is to account for the + # extra clock to do the conversion, and the low null bit returned at + # the start of the response. + resp = self._spi.transfer([command, 0x0, 0x0]) + # Parse out the 10 bits of response data and return it. + result = (resp[0] & 0x01) << 9 + result |= (resp[1] & 0xFF) << 1 + result |= (resp[2] & 0x80) >> 7 + return result & 0x3FF + + def read_adc_difference(self, differential): + """Read the difference between two channels. Differential should be a + value of: + - 0: Return channel 0 minus channel 1 + - 1: Return channel 1 minus channel 0 + - 2: Return channel 2 minus channel 3 + - 3: Return channel 3 minus channel 2 + - 4: Return channel 4 minus channel 5 + - 5: Return channel 5 minus channel 4 + - 6: Return channel 6 minus channel 7 + - 7: Return channel 7 minus channel 6 + """ + assert 0 <= differential <= 7, 'Differential number must be a value of 0-7!' + # Build a difference channel read command. + command = 0b10 << 6 # Start bit, differential read + command |= (differential & 0x07) << 3 # Channel number (in 3 bits) + # Note the bottom 3 bits of command are 0, this is to account for the + # extra clock to do the conversion, and the low null bit returned at + # the start of the response. + resp = self._spi.transfer([command, 0x0, 0x0]) + # Parse out the 10 bits of response data and return it. + result = (resp[0] & 0x01) << 9 + result |= (resp[1] & 0xFF) << 1 + result |= (resp[2] & 0x80) >> 7 + return result & 0x3FF diff --git a/Adafruit_Python_MCP3008/Adafruit_MCP3008/__init__.py b/Adafruit_Python_MCP3008/Adafruit_MCP3008/__init__.py new file mode 100644 index 0000000..767086c --- /dev/null +++ b/Adafruit_Python_MCP3008/Adafruit_MCP3008/__init__.py @@ -0,0 +1 @@ +from .MCP3008 import MCP3008 diff --git a/Adafruit_Python_MCP3008/LICENSE b/Adafruit_Python_MCP3008/LICENSE new file mode 100644 index 0000000..d025531 --- /dev/null +++ b/Adafruit_Python_MCP3008/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Adafruit Industries + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Adafruit_Python_MCP3008/README.md b/Adafruit_Python_MCP3008/README.md new file mode 100644 index 0000000..6b7da9a --- /dev/null +++ b/Adafruit_Python_MCP3008/README.md @@ -0,0 +1,19 @@ +# Adafruit Python MCP3008 + +Python code to use the MCP3008 analog to digital converter with a Raspberry Pi or BeagleBone black. + +## Installation + +To install the library from source (recommended) run the following commands on a Raspberry Pi or other Debian-based OS system: + + sudo apt-get install git build-essential python-dev + cd ~ + git clone https://github.com/adafruit/Adafruit_Python_MCP3008.git + cd Adafruit_Python_MCP3008 + sudo python setup.py install + +Alternatively you can install from pip with: + + sudo pip install adafruit-mcp3008 + +Note that the pip install method **won't** install the example code. diff --git a/Adafruit_Python_MCP3008/examples/differential.py b/Adafruit_Python_MCP3008/examples/differential.py new file mode 100644 index 0000000..df30e65 --- /dev/null +++ b/Adafruit_Python_MCP3008/examples/differential.py @@ -0,0 +1,38 @@ +# Simple example of reading the MCP3008 analog input channels using its +# differential mode. Will print the difference of channel 0 and 1. +# Author: Tony DiCola +# License: Public Domain +import time + +# Import SPI library (for hardware SPI) and MCP3008 library. +import Adafruit_GPIO.SPI as SPI +import Adafruit_MCP3008 + + +# Software SPI configuration: +# CLK = 18 +# MISO = 23 +# MOSI = 24 +# CS = 25 +# mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI) + +# Hardware SPI configuration: +SPI_PORT = 0 +SPI_DEVICE = 0 +mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) + +print('Press Ctrl-C to quit...') +while True: + # Grab the difference between channel 0 and 1 (i.e. channel 0 minus 1). + # Note you can specify any value in 0-7 to grab other differences: + # - 0: Return channel 0 minus channel 1 + # - 1: Return channel 1 minus channel 0 + # - 2: Return channel 2 minus channel 3 + # - 3: Return channel 3 minus channel 2 + # - 4: Return channel 4 minus channel 5 + # - 5: Return channel 5 minus channel 4 + # - 6: Return channel 6 minus channel 7 + # - 7: Return channel 7 minus channel 6 + value = mcp.read_adc_difference(0) + print('Channel 0 minus 1: {0}'.format(value)) + time.sleep(0.5) diff --git a/Adafruit_Python_MCP3008/examples/simpletest.py b/Adafruit_Python_MCP3008/examples/simpletest.py new file mode 100644 index 0000000..23f9f0c --- /dev/null +++ b/Adafruit_Python_MCP3008/examples/simpletest.py @@ -0,0 +1,39 @@ +# Simple example of reading the MCP3008 analog input channels and printing +# them all out. +# Author: Tony DiCola +# License: Public Domain +import time + +# Import SPI library (for hardware SPI) and MCP3008 library. +import Adafruit_GPIO.SPI as SPI +import Adafruit_MCP3008 + + +# Software SPI configuration: +CLK = 18 +MISO = 23 +MOSI = 24 +CS = 25 +mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI) + +# Hardware SPI configuration: +# SPI_PORT = 0 +# SPI_DEVICE = 0 +# mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) + + +print('Reading MCP3008 values, press Ctrl-C to quit...') +# Print nice channel column headers. +print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*range(8))) +print('-' * 57) +# Main program loop. +while True: + # Read all the ADC channel values in a list. + values = [0]*8 + for i in range(8): + # The read_adc function will get the value of the specified channel (0-7). + values[i] = mcp.read_adc(i) + # Print the ADC values. + print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*values)) + # Pause for half a second. + time.sleep(0.5) diff --git a/Adafruit_Python_MCP3008/ez_setup.py b/Adafruit_Python_MCP3008/ez_setup.py new file mode 100644 index 0000000..23ea9a2 --- /dev/null +++ b/Adafruit_Python_MCP3008/ez_setup.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python +"""Bootstrap setuptools installation + +To use setuptools in your package's setup.py, include this +file in the same directory and add this to the top of your setup.py:: + + from ez_setup import use_setuptools + use_setuptools() + +To require a specific version of setuptools, set a download +mirror, or use an alternate download directory, simply supply +the appropriate options to ``use_setuptools()``. + +This file can also be run as a script to install or upgrade setuptools. +""" +import os +import shutil +import sys +import tempfile +import zipfile +import optparse +import subprocess +import platform +import textwrap +import contextlib + +from distutils import log + +try: + from site import USER_SITE +except ImportError: + USER_SITE = None + +DEFAULT_VERSION = "3.5.1" +DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/" + +def _python_cmd(*args): + """ + Return True if the command succeeded. + """ + args = (sys.executable,) + args + return subprocess.call(args) == 0 + + +def _install(archive_filename, install_args=()): + with archive_context(archive_filename): + # installing + log.warn('Installing Setuptools') + if not _python_cmd('setup.py', 'install', *install_args): + log.warn('Something went wrong during the installation.') + log.warn('See the error message above.') + # exitcode will be 2 + return 2 + + +def _build_egg(egg, archive_filename, to_dir): + with archive_context(archive_filename): + # building an egg + log.warn('Building a Setuptools egg in %s', to_dir) + _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) + # returning the result + log.warn(egg) + if not os.path.exists(egg): + raise IOError('Could not build the egg.') + + +def get_zip_class(): + """ + Supplement ZipFile class to support context manager for Python 2.6 + """ + class ContextualZipFile(zipfile.ZipFile): + def __enter__(self): + return self + def __exit__(self, type, value, traceback): + self.close + return zipfile.ZipFile if hasattr(zipfile.ZipFile, '__exit__') else \ + ContextualZipFile + + +@contextlib.contextmanager +def archive_context(filename): + # extracting the archive + tmpdir = tempfile.mkdtemp() + log.warn('Extracting in %s', tmpdir) + old_wd = os.getcwd() + try: + os.chdir(tmpdir) + with get_zip_class()(filename) as archive: + archive.extractall() + + # going in the directory + subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) + os.chdir(subdir) + log.warn('Now working in %s', subdir) + yield + + finally: + os.chdir(old_wd) + shutil.rmtree(tmpdir) + + +def _do_download(version, download_base, to_dir, download_delay): + egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg' + % (version, sys.version_info[0], sys.version_info[1])) + if not os.path.exists(egg): + archive = download_setuptools(version, download_base, + to_dir, download_delay) + _build_egg(egg, archive, to_dir) + sys.path.insert(0, egg) + + # Remove previously-imported pkg_resources if present (see + # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details). + if 'pkg_resources' in sys.modules: + del sys.modules['pkg_resources'] + + import setuptools + setuptools.bootstrap_install_from = egg + + +def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, + to_dir=os.curdir, download_delay=15): + to_dir = os.path.abspath(to_dir) + rep_modules = 'pkg_resources', 'setuptools' + imported = set(sys.modules).intersection(rep_modules) + try: + import pkg_resources + except ImportError: + return _do_download(version, download_base, to_dir, download_delay) + try: + pkg_resources.require("setuptools>=" + version) + return + except pkg_resources.DistributionNotFound: + return _do_download(version, download_base, to_dir, download_delay) + except pkg_resources.VersionConflict as VC_err: + if imported: + msg = textwrap.dedent(""" + The required version of setuptools (>={version}) is not available, + and can't be installed while this script is running. Please + install a more recent version first, using + 'easy_install -U setuptools'. + + (Currently using {VC_err.args[0]!r}) + """).format(VC_err=VC_err, version=version) + sys.stderr.write(msg) + sys.exit(2) + + # otherwise, reload ok + del pkg_resources, sys.modules['pkg_resources'] + return _do_download(version, download_base, to_dir, download_delay) + +def _clean_check(cmd, target): + """ + Run the command to download target. If the command fails, clean up before + re-raising the error. + """ + try: + subprocess.check_call(cmd) + except subprocess.CalledProcessError: + if os.access(target, os.F_OK): + os.unlink(target) + raise + +def download_file_powershell(url, target): + """ + Download the file at url to target using Powershell (which will validate + trust). Raise an exception if the command cannot complete. + """ + target = os.path.abspath(target) + cmd = [ + 'powershell', + '-Command', + "(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)" % vars(), + ] + _clean_check(cmd, target) + +def has_powershell(): + if platform.system() != 'Windows': + return False + cmd = ['powershell', '-Command', 'echo test'] + devnull = open(os.path.devnull, 'wb') + try: + try: + subprocess.check_call(cmd, stdout=devnull, stderr=devnull) + except Exception: + return False + finally: + devnull.close() + return True + +download_file_powershell.viable = has_powershell + +def download_file_curl(url, target): + cmd = ['curl', url, '--silent', '--output', target] + _clean_check(cmd, target) + +def has_curl(): + cmd = ['curl', '--version'] + devnull = open(os.path.devnull, 'wb') + try: + try: + subprocess.check_call(cmd, stdout=devnull, stderr=devnull) + except Exception: + return False + finally: + devnull.close() + return True + +download_file_curl.viable = has_curl + +def download_file_wget(url, target): + cmd = ['wget', url, '--quiet', '--output-document', target] + _clean_check(cmd, target) + +def has_wget(): + cmd = ['wget', '--version'] + devnull = open(os.path.devnull, 'wb') + try: + try: + subprocess.check_call(cmd, stdout=devnull, stderr=devnull) + except Exception: + return False + finally: + devnull.close() + return True + +download_file_wget.viable = has_wget + +def download_file_insecure(url, target): + """ + Use Python to download the file, even though it cannot authenticate the + connection. + """ + try: + from urllib.request import urlopen + except ImportError: + from urllib2 import urlopen + src = dst = None + try: + src = urlopen(url) + # Read/write all in one block, so we don't create a corrupt file + # if the download is interrupted. + data = src.read() + dst = open(target, "wb") + dst.write(data) + finally: + if src: + src.close() + if dst: + dst.close() + +download_file_insecure.viable = lambda: True + +def get_best_downloader(): + downloaders = [ + download_file_powershell, + download_file_curl, + download_file_wget, + download_file_insecure, + ] + + for dl in downloaders: + if dl.viable(): + return dl + +def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, + to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader): + """ + Download setuptools from a specified location and return its filename + + `version` should be a valid setuptools version number that is available + as an egg for download under the `download_base` URL (which should end + with a '/'). `to_dir` is the directory where the egg will be downloaded. + `delay` is the number of seconds to pause before an actual download + attempt. + + ``downloader_factory`` should be a function taking no arguments and + returning a function for downloading a URL to a target. + """ + # making sure we use the absolute path + to_dir = os.path.abspath(to_dir) + zip_name = "setuptools-%s.zip" % version + url = download_base + zip_name + saveto = os.path.join(to_dir, zip_name) + if not os.path.exists(saveto): # Avoid repeated downloads + log.warn("Downloading %s", url) + downloader = downloader_factory() + downloader(url, saveto) + return os.path.realpath(saveto) + +def _build_install_args(options): + """ + Build the arguments to 'python setup.py install' on the setuptools package + """ + return ['--user'] if options.user_install else [] + +def _parse_args(): + """ + Parse the command line for options + """ + parser = optparse.OptionParser() + parser.add_option( + '--user', dest='user_install', action='store_true', default=False, + help='install in user site package (requires Python 2.6 or later)') + parser.add_option( + '--download-base', dest='download_base', metavar="URL", + default=DEFAULT_URL, + help='alternative URL from where to download the setuptools package') + parser.add_option( + '--insecure', dest='downloader_factory', action='store_const', + const=lambda: download_file_insecure, default=get_best_downloader, + help='Use internal, non-validating downloader' + ) + parser.add_option( + '--version', help="Specify which version to download", + default=DEFAULT_VERSION, + ) + options, args = parser.parse_args() + # positional arguments are ignored + return options + +def main(): + """Install or upgrade setuptools and EasyInstall""" + options = _parse_args() + archive = download_setuptools( + version=options.version, + download_base=options.download_base, + downloader_factory=options.downloader_factory, + ) + return _install(archive, _build_install_args(options)) + +if __name__ == '__main__': + sys.exit(main()) diff --git a/Adafruit_Python_MCP3008/setup.py b/Adafruit_Python_MCP3008/setup.py new file mode 100644 index 0000000..31bda9c --- /dev/null +++ b/Adafruit_Python_MCP3008/setup.py @@ -0,0 +1,30 @@ +try: + # Try using ez_setup to install setuptools if not already installed. + from ez_setup import use_setuptools + use_setuptools() +except ImportError: + # Ignore import error and assume Python 3 which already has setuptools. + pass + +from setuptools import setup, find_packages + +classifiers = ['Development Status :: 4 - Beta', + 'Operating System :: POSIX :: Linux', + 'License :: OSI Approved :: MIT License', + 'Intended Audience :: Developers', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Topic :: Software Development', + 'Topic :: System :: Hardware'] + +setup(name = 'Adafruit_MCP3008', + version = '1.0.2', + author = 'Tony DiCola', + author_email = 'tdicola@adafruit.com', + description = 'Python code to use the MCP3008 analog to digital converter with a Raspberry Pi or BeagleBone black.', + license = 'MIT', + classifiers = classifiers, + url = 'https://github.com/adafruit/Adafruit_Python_MCP3008/', + dependency_links = ['https://github.com/adafruit/Adafruit_Python_GPIO/tarball/master#egg=Adafruit-GPIO-0.6.5'], + install_requires = ['Adafruit-GPIO>=0.6.5'], + packages = find_packages()) |