Repository: pimoroni/blinkt Branch: master Commit: 27a7dfcd2672 Files: 92 Total size: 217.1 KB Directory structure: gitextract_952ablw2/ ├── .github/ │ └── workflows/ │ └── test.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── documentation/ │ └── REFERENCE.md ├── examples/ │ ├── 1d_tetris.py │ ├── README.md │ ├── anvil-colour-control.py │ ├── binary_clock.py │ ├── binary_clock_meld.py │ ├── blinkt_thermo.py │ ├── candle.py │ ├── cheerlights.py │ ├── cpu_load.py │ ├── cpu_temp.py │ ├── extra_examples/ │ │ ├── README.md │ │ ├── drum_hits.py │ │ ├── pov_rainbow.py │ │ └── spirit_level.py │ ├── eyedropper.py │ ├── gradient_graph.py │ ├── graph.py │ ├── half.py │ ├── kitt.py │ ├── larson.py │ ├── larson_hue.py │ ├── max.py │ ├── mem_load.py │ ├── morse_code.py │ ├── mqtt.py │ ├── off.py │ ├── pulse.py │ ├── rainbow.py │ ├── random_blink.py │ ├── random_blink_colours.py │ ├── resistor_clock.py │ ├── rgb.py │ ├── setall.py │ ├── setup.cfg │ ├── solid_colours.py │ ├── solid_colours2.py │ ├── solid_colours3.py │ ├── twitter_monitor.py │ ├── unionjack.py │ └── white.py ├── library/ │ ├── .coveragerc │ ├── CHANGELOG.txt │ ├── LICENSE.txt │ ├── MANIFEST.in │ ├── Makefile │ ├── README.md │ ├── README.rst │ ├── blinkt.py │ ├── setup.cfg │ ├── setup.py │ ├── tests/ │ │ ├── test_setup.py │ │ └── tools.py │ └── tox.ini ├── library_c/ │ ├── CHANGELOG.txt │ ├── MANIFEST.in │ ├── Makefile │ ├── README.md │ ├── README.txt │ ├── blinkt │ ├── blinkt.i │ ├── blinkt.py │ ├── blinkt_wrap.c │ ├── lib/ │ │ ├── blinkt.c │ │ └── blinkt.h │ └── setup.py ├── packaging/ │ ├── CHANGELOG │ ├── debian/ │ │ ├── README │ │ ├── changelog │ │ ├── clean │ │ ├── compat │ │ ├── control │ │ ├── copyright │ │ ├── docs │ │ ├── rules │ │ └── source/ │ │ ├── format │ │ └── options │ ├── makeall.sh │ ├── makedeb.sh │ ├── makedoc.sh │ └── makelog.sh ├── projects/ │ └── mqtt/ │ └── mqtt.py └── sphinx/ ├── _static/ │ └── custom.css ├── _templates/ │ ├── breadcrumbs.html │ └── layout.html ├── conf.py └── index.rst ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/test.yml ================================================ name: Python Tests on: pull_request: push: branches: - master jobs: test: runs-on: ubuntu-latest strategy: matrix: python: [2.7, 3.5, 3.7, 3.9] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python }} - name: Install Dependencies run: | python -m pip install --upgrade setuptools tox - name: Run Tests working-directory: library run: | tox -e py - name: Coverage env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} working-directory: library run: | python -m pip install coveralls coveralls --service=github if: ${{ matrix.python == '3.9' }} ================================================ FILE: .gitignore ================================================ build/ _build/ *.o *.so *.a *.py[cod] *.egg-info dist/ __pycache__ .DS_Store *.deb *.dsc *.build *.changes *.orig.* packaging/*tar.xz library/debian/ library/blinkt .coverage .tox/ .vscode/ .pytest_cache/ ================================================ FILE: Dockerfile ================================================ FROM resin/rpi-raspbian:jessie RUN apt-get update -qy && apt-get install -qy \ python \ python-rpi.gpio # Cancel out any Entrypoint already set in the base image. ENTRYPOINT [] WORKDIR /root/ COPY library library WORKDIR /root/library RUN python setup.py install WORKDIR /root/ COPY examples examples WORKDIR /root/examples/ CMD ["python", "larson.py"] ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2017 Pimoroni Ltd. 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. ================================================ FILE: README.md ================================================ ![Blinkt!](blinkt-logo.png) [![Build Status](https://travis-ci.com/pimoroni/blinkt.svg?branch=master)](https://travis-ci.com/pimoroni/blinkt) [![Coverage Status](https://coveralls.io/repos/github/pimoroni/blinkt/badge.svg?branch=master)](https://coveralls.io/github/pimoroni/blinkt?branch=master) [![PyPi Package](https://img.shields.io/pypi/v/blinkt.svg)](https://pypi.python.org/pypi/blinkt) [![Python Versions](https://img.shields.io/pypi/pyversions/blinkt.svg)](https://pypi.python.org/pypi/blinkt) https://shop.pimoroni.com/products/blinkt Eight super-bright RGB LED indicators, ideal for adding visual notifications to your Raspberry Pi on their own or on a pHAT stacking header. ## Installing ### Full install (recommended): We've created an easy installation script that will install all pre-requisites and get your Blinkt! up and running with minimal efforts. To run it, fire up Terminal which you'll find in Menu -> Accessories -> Terminal on your Raspberry Pi desktop, as illustrated below: ![Finding the terminal](http://get.pimoroni.com/resources/github-repo-terminal.png) In the new terminal window type the command exactly as it appears below (check for typos) and follow the on-screen instructions: ```bash curl https://get.pimoroni.com/blinkt | bash ``` Alternatively, on Raspbian, you can download the `pimoroni-dashboard` and install your product by browsing to the relevant entry: ```bash sudo apt-get install pimoroni ``` (you will find the Dashboard under 'Accessories' too, in the Pi menu - or just run `pimoroni-dashboard` at the command line) If you choose to download examples you'll find them in `/home/pi/Pimoroni/blinkt/`. ### Manual install: #### Library install for Python 3: on Raspbian: ```bash sudo apt-get install python3-blinkt ``` other environments: ```bash sudo pip3 install blinkt ``` #### Library install for Python 2: on Raspbian: ```bash sudo apt-get install python-blinkt ``` other environments: ```bash sudo pip2 install blinkt ``` ### Development: If you want to contribute, or like living on the edge of your seat by having the latest code, you should clone this repository, `cd` to the library directory, and run: ```bash sudo python3 setup.py install ``` (or `sudo python setup.py install` whichever your primary Python environment may be) ## Documentation & Support * Guides and tutorials - https://learn.pimoroni.com/blinkt * Function reference - http://docs.pimoroni.com/blinkt/ * GPIO Pinout - https://pinout.xyz/pinout/blinkt * Get help - http://forums.pimoroni.com/c/support ## Unofficial / Third-party libraries * Golang library & examples by [Alex Ellis](https://www.alexellis.io) - https://github.com/alexellis/blinkt_go, https://github.com/alexellis/blinkt_go_examples * Java library by Jim Darby - https://github.com/hackerjimbo/PiJava * Java library by @HoldYourWaffle - https://github.com/HoldYourWaffle/blinkt4j * Node.js library by @irrelon - https://github.com/irrelon/node-blinkt * Rust library by @golemparts - https://github.com/golemparts/blinkt ================================================ FILE: documentation/REFERENCE.md ================================================ # Blinkt Function Reference The two Blinkt methods you'll most commonly use are `set_pixel` and `show`. Here's a simple example: ``` from blinkt import set_pixel, show set_pixel(0,255,0,0) show() ``` `set_pixel` takes an optional fifth parameter; the brightness from 0.0 to 1.0. `set_pixel(pixel_no, red, green, blue, brightness)` You can also change the brightness with `set_brightness` from 0.0 to 1.0, for example: ``` from blinkt import set_brightness set_brightness(0.5) show() ``` Additionally, there exists a helper function `set_all` which allows you to set all pixels to the same color and brightness. The `brightness` parameter is just like the one in `set_pixel`: it's optional and ranges from 0.0 to 1.0. `set_all(red, green, blue, brightness)` ================================================ FILE: examples/1d_tetris.py ================================================ #!/usr/bin/env python import time from random import randint import blinkt MAX_SIZE = 4 MAX_GRID = blinkt.NUM_PIXELS + MAX_SIZE - 1 OFF = (0, 0, 0) grid = [OFF] * (MAX_GRID + 1) blinkt.set_clear_on_exit() # The tetris algorithm fail when random_color was 0,0,0 now avoided def random_color(): return (randint(0, 255), randint(0, 255), randint(1, 50)) def random_tile(max_size, min_size=1): return (randint(min_size, max_size), random_color()) def place(tile): for i in range(0, tile[0]): grid[MAX_GRID - i - len(tile)] = tile[1] def update(): for i in range(blinkt.NUM_PIXELS): blinkt.set_pixel(i, grid[i][0], grid[i][1], grid[i][2]) blinkt.show() def has_lines(): return grid[0] != OFF def get_lines(): lines = [] for i, color in enumerate(grid): if color == OFF: return lines else: lines.append(i) return lines def blink_lines(): def hide(): for line in get_lines(): blinkt.set_pixel(line, 0, 0, 0) blinkt.show() hide() time.sleep(0.5) update() time.sleep(0.5) hide() time.sleep(0.5) def remove_lines(): for line in get_lines(): grid[line] = OFF def gravity(): grid.append(OFF) grid.pop(0) def main(): blinkt.set_brightness(0.1) place(random_tile(MAX_SIZE)) update() while True: time.sleep(0.5) if has_lines(): blink_lines() remove_lines() place(random_tile(MAX_SIZE)) else: gravity() update() if __name__ == '__main__': main() ================================================ FILE: examples/README.md ================================================ ## Examples The examples in this directory should just work with Blinkt!, although you'll need to add Twitter developer access tokens and secrets in the `twitter_monitor.py` example. You can get these at [https://dev.twitter.com/](https://dev.twitter.com/), after setting up a new application. Where noted, the instructions for adding keys / installing modules are in the code itself. The examples in the `extra_examples` folder are designed to work with other pHATs and HATs, so be aware of that before trying them. ## List of examples with basic instructions - 1d_tetris - shows randomly coloured lights falling into place and clearing occasionally. No input needed. Offline. - binary_clock - shows time in hours, minutes, and seconds using the local time from your Pi. No input needed. Offline. - binary_clock_meld - shows time in hours (red), minutes (green) and seconds (blue) using local time from your Pi. No input needed. Offline. - blinkt_thermo - draws a graph of the temperature based on the openweather data for whatever city you set it to. Needs keys and ID from openweathermap.org. Online. - candle - flickers the pixels in a candle effect. May require a numpy install. Offline. - cheerlights - reads twitter for any tweets with the hashtag "cheerlights" and a colour. Changes all the pixels to that colour. Online. - cpu_load - shows a graph of cpu usage as a percentage. May require a psutil install. Offline. - cpu_temp - shows a graph of the cpu temperature as a percentage. Offline. - eyedropper - shows the rgb value at cursor location real time. Offline. - gradient_graph - pulses a rainbow across the blinkt and back again. Offline. - graph - pulses a magenta graph across the blinkt and back again. Offline. - larson - remember Knight Rider? Offline. - larson_hue - same as larson, but in rainbow colours! Offline. - mem_load - shows a graph of the memory load on the Pi as a percentage. Offline. - morse_code - shows a message in [warning: flashing] morse code. Change line 40 if you want a different message. Offline. - mqtt - send controls remotely to your Blinkt. May require a paho-mqtt install. Requires setup on another machine as per instructions in the code. Online. - pulse - pulses cyan light from the centre pixels to outer edges. Offline. - rainbow - shows a gently moving rainbow along the blinkt. Yay, rainbows! Offline. - random_blink - blinks yellow lights at random, like paparazzi in a crowd. Change colour on line 14 if you like. Offline. - random_blink_colours - imagine if the paparazzi were carrying pastel unicorns. Offline. - resistor_clock - shows the time in pairs of pixels, using resistor codes. Brown light (representing a 1) is a bit hard to see. Offline. - rgb - Run this one a bit differently. Type python rgb.py and then three values, eg python rgb.py 10 90 80 will make it turn on cyan, python rgb.py 100 0 0 will make it turn on red. Offline. - setup.cfg is NOT an example. - solid_colours - Flashes red, green, blue on repeat. You can change the colours on lines 14, 17 and 20. Offline. - twitter_monitor - Will show a notification when the hashtag of your choice (line 48) is mentioned on Twitter. You need to add consumer key, consumer secret, access token and access secret (see instructions at top of this document). Online. ================================================ FILE: examples/anvil-colour-control.py ================================================ # Basic example for controlling the Blinkt LED colours via Anvil # Learn more at: https://anvil.works/ # # Dependencies: # # python3 -m pip install blinkt colour anvil-uplink # # Run this example with: # # python3 anvil-colour-control.py # # You'll be prompted for an email address to set up the web control # portion of this example. # # Check your email, click the link and- when the app has loads - # hit the "Run" button at the top to start remote-controlling # your Blinkt! import blinkt from colour import Color from anvil.app_creator import create_app import anvil.server # Create the Blinkt demo app in your Anvil account app = create_app("blinkt") # Define functions that can be called from your Anvil app on the web anvil.server.connect(app.uplink_key) @anvil.server.callable def set_color(color_string): print("Setting LEDs to {}".format(color_string)) c = Color(color_string) blinkt.set_all(c.red * 255, c.green * 255, c.blue * 255, 1.0) blinkt.show() @anvil.server.callable def clear(): print("Clearing LEDs") blinkt.clear() blinkt.show() # Display the URL where you can control the Blinkt LEDS print("Control your Blinkt LEDs at {}".format(app.origin)) print("Press Ctrl-C to exit") # Keep the script running until the user exits with Ctrl-C anvil.server.wait_forever() ================================================ FILE: examples/binary_clock.py ================================================ #!/usr/bin/env python from time import localtime, sleep import blinkt blinkt.set_clear_on_exit() MODE_HOUR = 0 MODE_MIN = 1 MODE_SEC = 2 MODE_NAMES = {MODE_HOUR: 'Hour mode', MODE_MIN: 'Minute mode', MODE_SEC: 'Seconds mode'} time_to_stay_in_mode = 3 time_in_mode = 0 mode = 0 lh = 0 lm = 0 while True: t = localtime() h, m, s = t.tm_hour, t.tm_min, t.tm_sec if h != lh: mode = MODE_HOUR time_in_mode = 0 elif m != lm: mode = MODE_MIN time_in_mode = 0 lm = m lh = h blinkt.clear() if (s % 2) == 0: blinkt.set_pixel(1, 64, 64, 64) if mode == MODE_HOUR: blinkt.set_pixel(0, 255, 0, 0) for x in range(6): bit = (h & (1 << x)) > 0 r, g, b = [128 * bit] * 3 blinkt.set_pixel(7 - x, r, g, b) if mode == MODE_MIN: blinkt.set_pixel(0, 0, 255, 0) for x in range(6): bit = (m & (1 << x)) > 0 r, g, b = [128 * bit] * 3 blinkt.set_pixel(7 - x, r, g, b) if mode == MODE_SEC: blinkt.set_pixel(0, 0, 0, 255) for x in range(6): bit = (s & (1 << x)) > 0 r, g, b = [128 * bit] * 3 blinkt.set_pixel(7 - x, r, g, b) blinkt.show() print('{h:2d}:{m:02d}:{s:02d}; mode: {mode}; time in mode: {tim}'.format(h=h, m=m, s=s, mode=MODE_NAMES[mode], tim=time_in_mode)) time_in_mode += 1 if time_in_mode == time_to_stay_in_mode: mode += 1 mode %= 3 time_in_mode = 0 sleep(1) ================================================ FILE: examples/binary_clock_meld.py ================================================ #!/usr/bin/env python from time import localtime, sleep import blinkt print('Hour = Red, Minute = Green, Second = Blue') blinkt.set_clear_on_exit() blinkt.set_brightness(0.2) on_value = 64 while True: t = localtime() h, m, s = t.tm_hour, t.tm_min, t.tm_sec print('{h:2d}:{m:02d}:{s:02d}'.format(h=h, m=m, s=s)) blinkt.clear() # Blink LED 0 v = on_value * (s % 2) blinkt.set_pixel(0, v, v, v) for n in range(6): # Grab the n'th bit from hour, min and second bit_h = (h & (1 << n)) > 0 bit_m = (m & (1 << n)) > 0 bit_s = (s & (1 << n)) > 0 r, g, b = [int(c * on_value) for c in (bit_h, bit_m, bit_s)] blinkt.set_pixel(7 - n, r, g, b) blinkt.show() sleep(1) ================================================ FILE: examples/blinkt_thermo.py ================================================ #!/usr/bin/env python # Data from OpenWeatherMap # show_graph function adapted from cpu_temp.py from time import sleep from sys import exit try: import requests except ImportError: exit('This script requires the requests module\nInstall with: sudo pip install requests') import blinkt # Grab your API key here: http://openweathermap.org # List of city ID city.list.json.gz can be downloaded here http://bulk.openweathermap.org/sample/ API_KEY = '' CITY_ID = '' url = 'http://api.openweathermap.org/data/2.5/weather' temp = 0 def update_weather(): global temp payload = { 'id': CITY_ID, 'units': 'metric', 'appid': API_KEY } try: r = requests.get(url=url, params=payload) temp = r.json().get('main').get('temp') print('Temperture = ' + str(temp) + ' C') except requests.exceptions.ConnectionError: print('Connection Error') def show_graph(v, r, g, b): v *= blinkt.NUM_PIXELS for x in range(blinkt.NUM_PIXELS): if v < 0: r, g, b = 0, 0, 0 else: r, g, b = [int(min(v, 1.0) * c) for c in [r, g, b]] blinkt.set_pixel(x, r, g, b) v -= 1 blinkt.show() def draw_thermo(temp): v = temp v /= 40 v += (1 / 8) show_graph(v, 255, 0, 0) blinkt.set_brightness(0.1) while 1: update_weather() draw_thermo(temp) sleep(120) ================================================ FILE: examples/candle.py ================================================ #!/usr/bin/env python import colorsys import time from sys import exit try: import numpy as np except ImportError: exit('This script requires the numpy module\nInstall with: sudo apt install python3-numpy') import blinkt blinkt.clear() start = 0 end = 60 while True: wait = np.random.choice(np.random.noncentral_chisquare(5, 1, 1000), 1)[0] / 50 n = np.random.choice(np.random.noncentral_chisquare(5, 0.1, 1000), 1) limit = int(n[0]) if limit > blinkt.NUM_PIXELS: limit = blinkt.NUM_PIXELS for pixel in range(limit): hue = start + (((end - start) / float(blinkt.NUM_PIXELS)) * pixel) r, g, b = [int(c * 255) for c in colorsys.hsv_to_rgb(hue / 360.0, 1.0, 1.0)] blinkt.set_pixel(pixel, r, g, b) blinkt.show() time.sleep(0.05 / (pixel + 1)) time.sleep(wait) blinkt.clear() ================================================ FILE: examples/cheerlights.py ================================================ #!/usr/bin/env python import time from sys import exit try: import requests except ImportError: exit('This script requires the requests module\nInstall with: sudo pip install requests') import blinkt blinkt.set_clear_on_exit() def hex_to_rgb(col_hex): """Convert a hex colour to an RGB tuple.""" col_hex = col_hex.lstrip('#') return bytearray.fromhex(col_hex) while True: r = requests.get('http://api.thingspeak.com/channels/1417/field/2/last.json', timeout=2) json = r.json() if 'field2' not in json: print('Error {status}: {error}'.format(status=json['status'], error=json['error'])) time.sleep(5) continue r, g, b = hex_to_rgb(json['field2']) for i in range(blinkt.NUM_PIXELS): blinkt.set_pixel(i, r, g, b) blinkt.show() time.sleep(5) # Be friendly to the API ================================================ FILE: examples/cpu_load.py ================================================ #!/usr/bin/env python import time from sys import exit try: import psutil except ImportError: exit('This script requires the psutil module\nInstall with: sudo apt install python3-psutil') import blinkt blinkt.set_clear_on_exit() def show_graph(v, r, g, b): v *= blinkt.NUM_PIXELS for x in range(blinkt.NUM_PIXELS): if v < 0: r, g, b = 0, 0, 0 else: r, g, b = [int(min(v, 1.0) * c) for c in [r, g, b]] blinkt.set_pixel(x, r, g, b) v -= 1 blinkt.show() blinkt.set_brightness(0.1) while True: v = psutil.cpu_percent() / 100.0 show_graph(v, 255, 255, 255) time.sleep(0.01) ================================================ FILE: examples/cpu_temp.py ================================================ #!/usr/bin/env python import time from subprocess import PIPE, Popen import blinkt blinkt.set_clear_on_exit() def get_cpu_temperature(): process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE) output, _error = process.communicate() output = output.decode() pos_start = output.index('=') + 1 pos_end = output.rindex("'") temp = float(output[pos_start:pos_end]) return temp def show_graph(v, r, g, b): v *= blinkt.NUM_PIXELS for x in range(blinkt.NUM_PIXELS): if v < 0: r, g, b = 0, 0, 0 else: r, g, b = [int(min(v, 1.0) * c) for c in [r, g, b]] blinkt.set_pixel(x, r, g, b) v -= 1 blinkt.show() blinkt.set_brightness(0.1) while True: v = get_cpu_temperature() / 100.0 show_graph(v, 255, 255, 255) time.sleep(0.01) ================================================ FILE: examples/extra_examples/README.md ================================================ #Extra Examples The examples in this folder are designed to work with other pHATs and HATs: * drum_hits.py expects a Drum HAT to be available and the relevant Python library installed * pov_rainbow.py and spirit_level.py expects an Enviro pHAT to be available and the relevant Python library installed ================================================ FILE: examples/extra_examples/drum_hits.py ================================================ #!/usr/bin/env python import glob import os import time from sys import exit try: import drumhat except ImportError: exit('This script requires the drumhat module\nInstall with: sudo pip install drumhat') try: import pygame except ImportError: exit('This script requires the pygame module\nInstall with: sudo pip install pygame') import blinkt DRUM_FOLDER = 'drums2' BANK = os.path.join(os.path.dirname(__file__), DRUM_FOLDER) pygame.mixer.init(44100, -16, 1, 512) pygame.mixer.set_num_channels(16) files = glob.glob(os.path.join(BANK, '*.wav')) files.sort() samples = [pygame.mixer.Sound(f) for f in files] def show_all(state): for i in range(8): val = state * 255 blinkt.set_pixel(i, val, val, val) blinkt.show() def handle_hit(event): samples[event.channel].play(loops=0) show_all(1) print('You hit pad {}, playing: {}'.format(event.pad, files[event.channel])) def handle_release(): show_all(0) drumhat.on_hit(drumhat.PADS, handle_hit) drumhat.on_release(drumhat.PADS, handle_release) while True: time.sleep(1) ================================================ FILE: examples/extra_examples/pov_rainbow.py ================================================ #!/usr/bin/env python import time from colorsys import hsv_to_rgb from sys import exit try: from envirophat import motion except ImportError: exit('This script requires the envirophat module\nInstall with: sudo pip install envirophat') import blinkt offset = 0 direction = 0 t = [] t_start = 0 total_time = 1000 def millis(): return int(round(time.time() * 1000)) while True: x, y, z = motion.accelerometer() print(y) if y < -1.9 and not direction == -1: direction = -1 t.append(millis() - t_start) t_start = millis() t = t[-5:] if y > 1.9 and not direction == 1: direction = 1 t.append(millis() - t_start) t_start = millis() t = t[-5:] if len(t) > 0: total_time = float(sum(t)) / len(t) offset = ((millis() - t_start) / total_time) # offset += direction * 10 offset = min(1.0, offset) offset = max(0.0, offset) hue = offset if direction == -1: hue = 1.0 - offset r, g, b = [int(c * 255.0) for c in hsv_to_rgb(hue, 1.0, 1.0)] for x in range(8): blinkt.set_pixel(x, r, g, b) blinkt.show() time.sleep(0.0001) ================================================ FILE: examples/extra_examples/spirit_level.py ================================================ #!/usr/bin/env python import time from sys import exit try: from envirophat import motion except ImportError: exit('This script requires the envirophat module\nInstall with: sudo pip install envirophat') import blinkt x_avg = [] while True: x, y, z = motion.accelerometer() x_avg.append(x) x_avg = x_avg[-5:] x = float(sum(x_avg)) / len(x_avg) x = max(-1, x) x = min(1, x) blinkt.clear() if abs(x) < 0.05: blinkt.set_pixel(3, 0, 255, 0) blinkt.set_pixel(4, 0, 255, 0) elif x > 0: val = abs(x) * 4.0 for x in range(4): if val < 0: break blinkt.set_pixel(3 - x, int(255.0 * min(val, 1.0)), 0, 0) val -= 1 elif x < 0: val = abs(x) * 4.0 for x in range(4): if val < 0: break blinkt.set_pixel(4 + x, int(255.0 * min(val, 1.0)), 0, 0) val -= 1 blinkt.show() time.sleep(0.01) ================================================ FILE: examples/eyedropper.py ================================================ #!/usr/bin/env python3 from PIL import ImageGrab import pyautogui import blinkt import time print('Press Ctrl-C to quit.') try: while True: x, y = pyautogui.position() im = ImageGrab.grab(bbox=(x - 1, y, x, y + 1)) rawrgb = list(im.getdata()) rgb = str(rawrgb)[2:-2] r, g, b = rgb.split(', ') blinkt.set_all(r, g, b) blinkt.set_brightness(1) blinkt.show() time.sleep(0.01) except KeyboardInterrupt: print('\n') ================================================ FILE: examples/gradient_graph.py ================================================ #!/usr/bin/env python import colorsys import math import time import blinkt blinkt.set_clear_on_exit() hue_range = 120 hue_start = 0 max_brightness = 0.2 def show_graph(v, r, g, b): v *= blinkt.NUM_PIXELS for x in range(blinkt.NUM_PIXELS): hue = ((hue_start + ((x / float(blinkt.NUM_PIXELS)) * hue_range)) % 360) / 360.0 r, g, b = [int(c * 255) for c in colorsys.hsv_to_rgb(hue, 1.0, 1.0)] if v < 0: brightness = 0 else: brightness = min(v, 1.0) * max_brightness blinkt.set_pixel(x, r, g, b, brightness) v -= 1 blinkt.show() blinkt.set_brightness(0.1) try: while True: t = time.time() * 2 v = (math.sin(t) + 1) / 2 # Get a value between 0 and 1 show_graph(v, 255, 0, 255) time.sleep(0.01) except KeyboardInterrupt: pass ================================================ FILE: examples/graph.py ================================================ #!/usr/bin/env python import math import time import blinkt blinkt.set_clear_on_exit() def show_graph(v, r, g, b): v *= blinkt.NUM_PIXELS for x in range(blinkt.NUM_PIXELS): if v < 0: r, g, b = 0, 0, 0 else: r, g, b = [int(min(v, 1.0) * c) for c in [r, g, b]] blinkt.set_pixel(x, r, g, b) v -= 1 blinkt.show() blinkt.set_brightness(0.1) try: while True: t = time.time() v = (math.sin(t) + 1) / 2 # Get a value between 0 and 1 show_graph(v, 255, 0, 255) time.sleep(0.01) except KeyboardInterrupt: pass ================================================ FILE: examples/half.py ================================================ #!/usr/bin/env python import blinkt blinkt.set_clear_on_exit(False) blinkt.set_all(255, 255, 255, 0.5) blinkt.show() ================================================ FILE: examples/kitt.py ================================================ #!/usr/bin/env python import time # so we can wait between frames import blinkt # so we can talk to our blinkt lights! BRIGHTNESS = 0.2 # range is 0.0 to 1.0 MAX_COLOUR = 255 # range is 0 to 255 DECAY_FACTOR = 1.5 # how quickly should MAX_COLOUR fade? (1.5 works well) TIME_SLEEP = 0.04 # seconds (0.04 works well) PIXELS = blinkt.NUM_PIXELS # usually 8, can use fewer if you like! blinkt.clear # make all pixels blank / black blinkt.set_brightness(BRIGHTNESS) brightpixel = -1 direction = 1 print('Hello Michael.\nHow are you today?') while True: # decay all pixels for x in range(PIXELS): pixel = blinkt.get_pixel(x) # format is [ r, g, b, brightness? ] blinkt.set_pixel(x, pixel[0] / DECAY_FACTOR, 0, 0) # brightpixel should move back and forth all the pixels, # in a ping-pong, triangle wave. Not (co)sine. brightpixel += direction if brightpixel >= PIXELS - 1: brightpixel = PIXELS - 1 direction = - abs(direction) if brightpixel <= 0: brightpixel = 0 direction = abs(direction) blinkt.set_pixel(brightpixel, MAX_COLOUR, 0, 0) blinkt.show() # draw the lights! time.sleep(TIME_SLEEP) # wait a bit before working on next frame ================================================ FILE: examples/larson.py ================================================ #!/usr/bin/env python import time import blinkt blinkt.set_clear_on_exit() REDS = [0, 0, 0, 0, 0, 16, 64, 255, 64, 16, 0, 0, 0, 0, 0, 0] start_time = time.time() while True: # Sine wave, spends a little longer at min/max # delta = (time.time() - start_time) * 8 # offset = int(round(((math.sin(delta) + 1) / 2) * (blinkt.NUM_PIXELS - 1))) # Triangle wave, a snappy ping-pong effect delta = (time.time() - start_time) * 16 offset = int(abs((delta % len(REDS)) - blinkt.NUM_PIXELS)) for i in range(blinkt.NUM_PIXELS): blinkt.set_pixel(i, REDS[offset + i], 0, 0) blinkt.show() time.sleep(0.1) ================================================ FILE: examples/larson_hue.py ================================================ #!/usr/bin/env python import math import time import colorsys import blinkt FALLOFF = 1.9 SCAN_SPEED = 4 blinkt.set_clear_on_exit() start_time = time.time() while True: delta = (time.time() - start_time) # Offset is a sine wave derived from the time delta # we use this to animate both the hue and larson scan # so they are kept in sync with each other offset = (math.sin(delta * SCAN_SPEED) + 1) / 2 # Use offset to pick the right colour from the hue wheel hue = int(round(offset * 360)) # Maximum number basex on NUM_PIXELS max_val = blinkt.NUM_PIXELS - 1 # Now we generate a value from 0 to max_val offset = int(round(offset * max_val)) for x in range(blinkt.NUM_PIXELS): sat = 1.0 val = max_val - (abs(offset - x) * FALLOFF) val /= float(max_val) # Convert to 0.0 to 1.0 val = max(val, 0.0) # Ditch negative values xhue = hue # Grab hue for this pixel xhue += (1 - val) * 10 # Use the val offset to give a slight colour trail variation xhue %= 360 # Clamp to 0-359 xhue /= 360.0 # Convert to 0.0 to 1.0 r, g, b = [int(c * 255) for c in colorsys.hsv_to_rgb(xhue, sat, val)] blinkt.set_pixel(x, r, g, b, val / 4) blinkt.show() time.sleep(0.001) ================================================ FILE: examples/max.py ================================================ #!/usr/bin/env python import blinkt blinkt.set_clear_on_exit(False) blinkt.set_all(255, 255, 255, 1.0) blinkt.show() ================================================ FILE: examples/mem_load.py ================================================ #!/usr/bin/env python import time from sys import exit try: import psutil except ImportError: exit('This script requires the psutil module\nInstall with: sudo apt install python3-psutil') import blinkt blinkt.set_clear_on_exit() def show_graph(v, r, g, b): v *= blinkt.NUM_PIXELS for x in range(blinkt.NUM_PIXELS): if v < 0: r, g, b = 0, 0, 0 else: r, g, b = [int(min(v, 1.0) * c) for c in [r, g, b]] blinkt.set_pixel(x, r, g, b) v -= 1 blinkt.show() blinkt.set_brightness(0.1) while True: v = psutil.virtual_memory().percent / 100.0 show_graph(v, 255, 0, 255) time.sleep(0.01) ================================================ FILE: examples/morse_code.py ================================================ #!/usr/bin/env python import time import blinkt blinkt.set_clear_on_exit() def show_all(state): """Set all LEDs.""" for i in range(blinkt.NUM_PIXELS): val = state * 255 blinkt.set_pixel(i, val, val, val) blinkt.show() def dot(): """Blink LEDs for 0.05 seconds.""" show_all(1) time.sleep(0.05) show_all(0) time.sleep(0.2) def dash(): """Blink LEDs for 0.2 seconds.""" show_all(1) time.sleep(0.2) show_all(0) time.sleep(0.2) def space(): """Delay for 0.02 seconds.""" time.sleep(0.2) # 0 is a space, 1 is a dot and 2 is a dash MORSE = ' -... .. . -.. - -. . - . - -. -. - ' while True: for m in MORSE: if m == ' ': space() elif m == '.': dot() elif m == '-': dash() ================================================ FILE: examples/mqtt.py ================================================ #!/usr/bin/env python from sys import exit try: import paho.mqtt.client as mqtt except ImportError: exit('This example requires the paho-mqtt module\nInstall with: sudo pip install paho-mqtt') import blinkt MQTT_SERVER = 'iot.eclipse.org' MQTT_PORT = 1883 MQTT_TOPIC = 'pimoroni/blinkt' # Set these to use authorisation MQTT_USER = None MQTT_PASS = None print(""" MQTT Blinkt! Control This example uses public MQTT messages from {server} on port {port} to control Blinkt! It will monitor the {topic} topic by default, and understands the following messages: rgb,,,, - Set a single pixel to an RGB colour. Example: rgb,1,255,0,255 clr - Clear Blinkt! You can use the online MQTT tester at http://www.hivemq.com/demos/websocket-client/ to send messages. Use {server} as the host, and port 80 (Eclipse's websocket port). Set the topic to topic: {topic} """.format( server=MQTT_SERVER, port=MQTT_PORT, topic=MQTT_TOPIC )) def on_connect(client, userdata, flags, rc): print('Connected with result code ' + str(rc)) client.subscribe(MQTT_TOPIC) def on_message(client, userdata, msg): data = msg.payload if type(data) is bytes: data = data.decode('utf-8') data = data.split(',') command = data.pop(0) if command == 'clr' and len(data) == 0: blinkt.clear() blinkt.show() return if command == 'rgb' and len(data) == 4: try: pixel = data.pop(0) if pixel == '*': pixel = None else: pixel = int(pixel) if pixel > 7: print('Pixel out of range: ' + str(pixel)) return r, g, b = [int(x) & 0xff for x in data] print(command, pixel, r, g, b) except ValueError: print('Malformed command: ' + str(msg.payload)) return if pixel is None: for x in range(blinkt.NUM_PIXELS): blinkt.set_pixel(x, r, g, b) else: blinkt.set_pixel(pixel, r, g, b) blinkt.show() return blinkt.set_clear_on_exit() client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message if MQTT_USER is not None and MQTT_PASS is not None: print('Using username: {un} and password: {pw}'.format(un=MQTT_USER, pw='*' * len(MQTT_PASS))) client.username_pw_set(username=MQTT_USER, password=MQTT_PASS) client.connect(MQTT_SERVER, MQTT_PORT, 60) client.loop_forever() ================================================ FILE: examples/off.py ================================================ #!/usr/bin/env python import blinkt blinkt.clear() blinkt.show() ================================================ FILE: examples/pulse.py ================================================ #!/usr/bin/env python import colorsys import time from sys import exit try: import numpy as np except ImportError: exit('This script requires the numpy module\nInstall with: sudo pip install numpy') import blinkt blinkt.set_clear_on_exit() def make_gaussian(fwhm): x = np.arange(0, blinkt.NUM_PIXELS, 1, float) y = x[:, np.newaxis] x0, y0 = 3.5, 3.5 fwhm = fwhm gauss = np.exp(-4 * np.log(2) * ((x - x0) ** 2 + (y - y0) ** 2) / fwhm ** 2) return gauss while True: for z in list(range(1, 10)[::-1]) + list(range(1, 10)): fwhm = 5.0 / z gauss = make_gaussian(fwhm) start = time.time() y = 4 for x in range(blinkt.NUM_PIXELS): h = 0.5 s = 1.0 v = gauss[x, y] rgb = colorsys.hsv_to_rgb(h, s, v) r, g, b = [int(255.0 * i) for i in rgb] blinkt.set_pixel(x, r, g, b) blinkt.show() end = time.time() t = end - start if t < 0.04: time.sleep(0.04 - t) ================================================ FILE: examples/rainbow.py ================================================ #!/usr/bin/env python import colorsys import time import blinkt spacing = 360.0 / 16.0 hue = 0 blinkt.set_clear_on_exit() blinkt.set_brightness(0.1) while True: hue = int(time.time() * 100) % 360 for x in range(blinkt.NUM_PIXELS): offset = x * spacing h = ((hue + offset) % 360) / 360.0 r, g, b = [int(c * 255) for c in colorsys.hsv_to_rgb(h, 1.0, 1.0)] blinkt.set_pixel(x, r, g, b) blinkt.show() time.sleep(0.001) ================================================ FILE: examples/random_blink.py ================================================ #!/usr/bin/env python import random import time import blinkt blinkt.set_clear_on_exit() while True: pixels = random.sample(range(blinkt.NUM_PIXELS), random.randint(1, 5)) for i in range(blinkt.NUM_PIXELS): if i in pixels: blinkt.set_pixel(i, 255, 150, 0) else: blinkt.set_pixel(i, 0, 0, 0) blinkt.show() time.sleep(0.05) ================================================ FILE: examples/random_blink_colours.py ================================================ #!/usr/bin/env python import random import time import blinkt blinkt.set_clear_on_exit() blinkt.set_brightness(0.1) while True: for i in range(blinkt.NUM_PIXELS): blinkt.set_pixel(i, random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) blinkt.show() time.sleep(0.05) ================================================ FILE: examples/resistor_clock.py ================================================ #!/usr/bin/env python import time import blinkt colours = [ [0, 0, 0], # 0 black [139, 69, 19], # 1 brown [255, 0, 0], # 2 red [255, 69, 0], # 3 orange [255, 255, 0], # 4 yellow [0, 255, 0], # 5 green [0, 0, 255], # 6 blue [128, 0, 128], # 7 violet [255, 255, 100], # 8 grey [255, 255, 255], # 9 white ] blinkt.set_clear_on_exit() while True: hour = time.localtime().tm_hour minute = time.localtime().tm_min hourten = int(hour / 10) hourunit = int(hour % 10) minuteten = int(minute / 10) minuteunit = int(minute % 10) r, g, b = colours[hourten] blinkt.set_pixel(0, r, g, b) blinkt.set_pixel(1, r, g, b) r, g, b = colours[hourunit] blinkt.set_pixel(2, r, g, b) blinkt.set_pixel(3, r, g, b) r, g, b = colours[minuteten] blinkt.set_pixel(4, r, g, b) blinkt.set_pixel(5, r, g, b) r, g, b = colours[minuteunit] blinkt.set_pixel(6, r, g, b) blinkt.set_pixel(7, r, g, b) blinkt.show() time.sleep(0.5) blinkt.set_pixel(7, 0, 0, 0) blinkt.show() time.sleep(0.5) ================================================ FILE: examples/rgb.py ================================================ #!/usr/bin/env python import sys import blinkt def usage(): print('Usage: {} '.format(sys.argv[0])) sys.exit(1) if len(sys.argv) != 4: usage() # Exit if non integer value. int() will raise a ValueError try: r, g, b = [int(x) for x in sys.argv[1:]] except ValueError: usage() # Exit if any of r, g, b are greater than 255 if max(r, g, b) > 255: usage() print('Setting Blinkt to {r},{g},{b}'.format(r=r, g=g, b=b)) blinkt.set_clear_on_exit(False) blinkt.set_all(r, g, b) blinkt.show() ================================================ FILE: examples/setall.py ================================================ #!/usr/bin/env python import sys from sys import argv import blinkt if len(argv) < 4 or len(argv) > 5: sys.stderr.write("Syntax: {0} [brightness]\n".format(argv[0])) exit(1) red = int(argv[1]) green = int(argv[2]) blue = int(argv[3]) bright = float(argv[4]) if len(argv) > 4 else None blinkt.set_clear_on_exit(False) blinkt.set_all(red, green, blue, bright) blinkt.show() ================================================ FILE: examples/setup.cfg ================================================ [flake8] ignore= D100 # Ignore various docstring reqs D101 D102 D103 E501 # Ignore long lines ================================================ FILE: examples/solid_colours.py ================================================ #!/usr/bin/env python import time import blinkt blinkt.set_clear_on_exit() step = 0 while True: if step == 0: blinkt.set_all(128, 0, 0) if step == 1: blinkt.set_all(0, 128, 0) if step == 2: blinkt.set_all(0, 0, 128) step += 1 step %= 3 blinkt.show() time.sleep(0.5) ================================================ FILE: examples/solid_colours2.py ================================================ #!/usr/bin/env python import time import blinkt blinkt.set_clear_on_exit() step = 0 while True: if step == 0: blinkt.set_all(128, 0, 0) elif step == 1: blinkt.set_all(0, 128, 0) elif step == 2: blinkt.set_all(128, 128, 0) elif step == 3: blinkt.set_all(0, 0, 128) elif step == 4: blinkt.set_all(128, 0, 128) elif step == 5: blinkt.set_all(0, 128, 128) elif step == 6: blinkt.set_all(128, 128, 128) step += 1 step %= 7 blinkt.show() time.sleep(0.5) ================================================ FILE: examples/solid_colours3.py ================================================ #!/usr/bin/env python import time import blinkt blinkt.set_clear_on_exit() step = 0 while True: for i in range(0, 128): j = 128 - i if step == 0: blinkt.set_all(128, j, j) elif step == 1: blinkt.set_all(j, i, 0) elif step == 2: blinkt.set_all(i, 128, 0) elif step == 3: blinkt.set_all(j, j, i) elif step == 4: blinkt.set_all(i, 0, 128) elif step == 5: blinkt.set_all(j, i, 128) elif step == 6: blinkt.set_all(i, 128, 128) blinkt.show() time.sleep(0.01) step += 1 step %= 7 time.sleep(0.5) ================================================ FILE: examples/twitter_monitor.py ================================================ #!/usr/bin/env python import time from sys import exit try: from tweepy import Stream, OAuthHandler from tweepy.streaming import StreamListener except ImportError: exit('This script requires the tweepy module\nInstall with: sudo pip install tweepy') import blinkt ckey = '' # Consumer key csecret = '' # Consumer secret atoken = '' # Access token asecret = '' # Access secret class listener(StreamListener): def on_data(self, data): blink_blinkt() return True def on_error(self, status): print(status) def blink_blinkt(): for i in range(3): for j in range(blinkt.NUM_PIXELS): blinkt.set_pixel(j, 255, 0, 0) blinkt.show() time.sleep(0.1) for j in range(blinkt.NUM_PIXELS): blinkt.set_pixel(j, 0, 0, 0) blinkt.show() time.sleep(0.2) auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) twitterstream = Stream(auth, listener()) twitterstream.filter(track=['#INSERTHASHTAGHERE']) ================================================ FILE: examples/unionjack.py ================================================ #!/usr/bin/env python import time import blinkt RED__ = (255, 0, 0) WHITE = (127, 127, 127) BLUE_ = (0, 0, 255) pattern = [ [RED__, BLUE_, WHITE, RED__, RED__, WHITE, BLUE_, RED__], [BLUE_, RED__, WHITE, RED__, RED__, WHITE, RED__, BLUE_], [WHITE, WHITE, WHITE, RED__, RED__, WHITE, WHITE, WHITE], [RED__, RED__, RED__, RED__, RED__, RED__, RED__, RED__], [RED__, RED__, RED__, RED__, RED__, RED__, RED__, RED__], [WHITE, WHITE, WHITE, RED__, RED__, WHITE, WHITE, WHITE], [BLUE_, RED__, WHITE, RED__, RED__, WHITE, RED__, BLUE_], [RED__, BLUE_, WHITE, RED__, RED__, WHITE, BLUE_, RED__], ] blinkt.set_clear_on_exit() blinkt.set_brightness(0.1) while 1: for line in pattern: for i, pixel in enumerate(line): r, g, b = pixel blinkt.set_pixel(i, r, g, b) blinkt.show() time.sleep(0.25) ================================================ FILE: examples/white.py ================================================ #!/usr/bin/env python import blinkt blinkt.set_clear_on_exit(False) blinkt.set_all(255, 255, 255, 1.0) blinkt.show() ================================================ FILE: library/.coveragerc ================================================ [run] source = blinkt omit = .tox/* ================================================ FILE: library/CHANGELOG.txt ================================================ 0.1.2 ----- * BugFix: Added sleep to data output, see: https://github.com/pimoroni/blinkt/issues/62 0.1.1 ----- * New: Added `get_pixel` to return colour and brightness of a single pixel 0.1.0 ----- * Removed try/except from RPi.GPIO import, output was misleading at best * Reverted default behaviour of clear on exit 0.0.9 ----- * Added set_all method to set all pixels * Changed default behaviour of clear on exit to reduce module side-effects * Move GPIO initialisation to show() to reduce module side-effects 0.0.8 ----- * Tweaked some methods to show intent as implementation detail only * Added docstrings detailing public methods 0.0.7 ----- * Fixed bug with APA102 pixels that have a small, black die (vs the larger, paler one) 0.0.6 ----- * set_clear_on_exit now method 0.0.5 ----- * Range clamping and coercion to integers 0.0.4 ----- * Various bug fixes 0.0.3 ----- * Switch to Python 0.0.2 ----- * Bug fixes for C Library 0.0.1 ----- * Original C Library ================================================ FILE: library/LICENSE.txt ================================================ The MIT License (MIT) Copyright (c) 2016 Pimoroni Ltd 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. ================================================ FILE: library/MANIFEST.in ================================================ include CHANGELOG.txt include LICENSE.txt include README.rst include setup.py include blinkt.py ================================================ FILE: library/Makefile ================================================ all: gcc -Wall -DTEST lib/blinkt.c -l bcm2835 -o blinkt devel: -rm -r build python setup.py build sudo python setup.py develop ================================================ FILE: library/README.md ================================================ #Blinkt Pure Python Library ================================================ FILE: library/README.rst ================================================ .. figure:: blinkt-logo.png :alt: Blinkt! Blinkt! |Build Status| |Coverage Status| |PyPi Package| |Python Versions| https://shop.pimoroni.com/products/blinkt Eight super-bright RGB LED indicators, ideal for adding visual notifications to your Raspberry Pi on their own or on a pHAT stacking header. Installing ---------- Full install (recommended): ~~~~~~~~~~~~~~~~~~~~~~~~~~~ We've created an easy installation script that will install all pre-requisites and get your Blinkt! up and running with minimal efforts. To run it, fire up Terminal which you'll find in Menu -> Accessories -> Terminal on your Raspberry Pi desktop, as illustrated below: .. figure:: http://get.pimoroni.com/resources/github-repo-terminal.png :alt: Finding the terminal Finding the terminal In the new terminal window type the command exactly as it appears below (check for typos) and follow the on-screen instructions: .. code:: bash curl https://get.pimoroni.com/blinkt | bash Alternatively, on Raspbian, you can download the ``pimoroni-dashboard`` and install your product by browsing to the relevant entry: .. code:: bash sudo apt-get install pimoroni (you will find the Dashboard under 'Accessories' too, in the Pi menu - or just run ``pimoroni-dashboard`` at the command line) If you choose to download examples you'll find them in ``/home/pi/Pimoroni/blinkt/``. Manual install: ~~~~~~~~~~~~~~~ Library install for Python 3: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ on Raspbian: .. code:: bash sudo apt-get install python3-blinkt other environments: .. code:: bash sudo pip3 install blinkt Library install for Python 2: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ on Raspbian: .. code:: bash sudo apt-get install python-blinkt other environments: .. code:: bash sudo pip2 install blinkt Development: ~~~~~~~~~~~~ If you want to contribute, or like living on the edge of your seat by having the latest code, you should clone this repository, ``cd`` to the library directory, and run: .. code:: bash sudo python3 setup.py install (or ``sudo python setup.py install`` whichever your primary Python environment may be) Documentation & Support ----------------------- - Guides and tutorials - https://learn.pimoroni.com/blinkt - Function reference - http://docs.pimoroni.com/blinkt/ - GPIO Pinout - https://pinout.xyz/pinout/blinkt - Get help - http://forums.pimoroni.com/c/support Unofficial / Third-party libraries ---------------------------------- - Golang library & examples by `Alex Ellis `__ - https://github.com/alexellis/blinkt\_go\_examples - Java library by Jim Darby - https://github.com/hackerjimbo/PiJava .. |Build Status| image:: https://travis-ci.com/pimoroni/blinkt.svg?branch=master :target: https://travis-ci.com/pimoroni/blinkt .. |Coverage Status| image:: https://coveralls.io/repos/github/pimoroni/blinkt/badge.svg?branch=master :target: https://coveralls.io/github/pimoroni/blinkt?branch=master .. |PyPi Package| image:: https://img.shields.io/pypi/v/blinkt.svg :target: https://pypi.python.org/pypi/blinkt .. |Python Versions| image:: https://img.shields.io/pypi/pyversions/blinkt.svg :target: https://pypi.python.org/pypi/blinkt ================================================ FILE: library/blinkt.py ================================================ """Library for the Pimoroni Blinkt! - 8-pixel APA102 LED display.""" import atexit import time import RPi.GPIO as GPIO __version__ = '0.1.2' DAT = 23 CLK = 24 NUM_PIXELS = 8 BRIGHTNESS = 7 pixels = [[0, 0, 0, BRIGHTNESS]] * NUM_PIXELS sleep_time = 0 _gpio_setup = False _clear_on_exit = True def _exit(): if _clear_on_exit: clear() show() GPIO.cleanup() def set_brightness(brightness): """Set the brightness of all pixels. :param brightness: Brightness: 0.0 to 1.0 """ if brightness < 0 or brightness > 1: raise ValueError('Brightness should be between 0.0 and 1.0') for x in range(NUM_PIXELS): pixels[x][3] = int(31.0 * brightness) & 0b11111 def clear(): """Clear the pixel buffer.""" for x in range(NUM_PIXELS): pixels[x][0:3] = [0, 0, 0] def _write_byte(byte): for x in range(8): GPIO.output(DAT, byte & 0b10000000) GPIO.output(CLK, 1) time.sleep(sleep_time) byte <<= 1 GPIO.output(CLK, 0) time.sleep(sleep_time) # Emit exactly enough clock pulses to latch the small dark die APA102s which are weird # for some reason it takes 36 clocks, the other IC takes just 4 (number of pixels/2) def _eof(): GPIO.output(DAT, 0) for x in range(36): GPIO.output(CLK, 1) time.sleep(sleep_time) GPIO.output(CLK, 0) time.sleep(sleep_time) def _sof(): GPIO.output(DAT, 0) for x in range(32): GPIO.output(CLK, 1) time.sleep(sleep_time) GPIO.output(CLK, 0) time.sleep(sleep_time) def show(): """Output the buffer to Blinkt!.""" global _gpio_setup if not _gpio_setup: GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(DAT, GPIO.OUT) GPIO.setup(CLK, GPIO.OUT) atexit.register(_exit) _gpio_setup = True _sof() for pixel in pixels: r, g, b, brightness = pixel _write_byte(0b11100000 | brightness) _write_byte(b) _write_byte(g) _write_byte(r) _eof() def set_all(r, g, b, brightness=None): """Set the RGB value and optionally brightness of all pixels. If you don't supply a brightness value, the last value set for each pixel be kept. :param r: Amount of red: 0 to 255 :param g: Amount of green: 0 to 255 :param b: Amount of blue: 0 to 255 :param brightness: Brightness: 0.0 to 1.0 (default around 0.2) """ for x in range(NUM_PIXELS): set_pixel(x, r, g, b, brightness) def get_pixel(x): """Get the RGB and brightness value of a specific pixel. :param x: The horizontal position of the pixel: 0 to 7 """ r, g, b, brightness = pixels[x] brightness /= 31.0 return r, g, b, round(brightness, 3) def set_pixel(x, r, g, b, brightness=None): """Set the RGB value, and optionally brightness, of a single pixel. If you don't supply a brightness value, the last value will be kept. :param x: The horizontal position of the pixel: 0 to 7 :param r: Amount of red: 0 to 255 :param g: Amount of green: 0 to 255 :param b: Amount of blue: 0 to 255 :param brightness: Brightness: 0.0 to 1.0 (default around 0.2) """ if brightness is None: brightness = pixels[x][3] else: brightness = int(31.0 * brightness) & 0b11111 pixels[x] = [int(r) & 0xff, int(g) & 0xff, int(b) & 0xff, brightness] def set_clear_on_exit(value=True): """Set whether Blinkt! should be cleared upon exit. By default Blinkt! will turn off the pixels on exit, but calling:: blinkt.set_clear_on_exit(False) Will ensure that it does not. :param value: True or False (default True) """ global _clear_on_exit _clear_on_exit = value ================================================ FILE: library/setup.cfg ================================================ [flake8] exclude = test.py .tox, .eggs, .git, __pycache__, build, dist ignore = E501 ================================================ FILE: library/setup.py ================================================ #!/usr/bin/env python """ Copyright (c) 2016 Pimoroni. 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. """ try: from setuptools import setup except ImportError: from distutils.core import setup classifiers = ['Development Status :: 5 - Production/Stable', 'Operating System :: POSIX :: Linux', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Software Development', 'Topic :: System :: Hardware'] setup( name='blinkt', version='0.1.2', author='Philip Howard', author_email='phil@pimoroni.com', description="""Python library for driving Pimoroni Blinkt!""", long_description=open('README.rst').read() + '\n' + open('CHANGELOG.txt').read(), license='MIT', keywords='Raspberry Pi LED', url='http://www.pimoroni.com', classifiers=classifiers, py_modules=['blinkt'], install_requires=['RPi.GPIO'] ) ================================================ FILE: library/tests/test_setup.py ================================================ """Test Blinkt! basis initialisation.""" import mock import sys from tools import GPIO def test_setup(): """Test init succeeds and GPIO pins are setup.""" gpio = GPIO() sys.modules['RPi'] = mock.Mock() sys.modules['RPi'].GPIO = gpio sys.modules['RPi.GPIO'] = gpio import blinkt blinkt.show() assert gpio.pin_modes[blinkt.DAT] == gpio.OUT assert gpio.pin_modes[blinkt.CLK] == gpio.OUT ================================================ FILE: library/tests/tools.py ================================================ # noqa D100 class GPIO: """Mock RPi.GPIO class. Stubs out enough of RPi.GPIO to validate pin states are set correctly. """ BCM = 1 OUT = 1 IN = 1 def __init__(self): # noqa D100 self.pin_modes = {} self.pin_states = {} def output(self, pin, value): # noqa D100 self.pin_states[pin] = value def setmode(self, mode): # noqa D100 pass def setwarnings(self, mode): # noqa D100 pass def setup(self, pin, mode): # noqa D100 self.pin_modes[pin] = mode def cleanup(self): # noqa D100 pass ================================================ FILE: library/tox.ini ================================================ [tox] envlist = py{27,35,37,39},qa skip_missing_interpreters = True [testenv] commands = python setup.py install coverage run -m py.test -v -r wsx coverage report deps = mock pytest>=3.1 pytest-cov [testenv:qa] commands = flake8 flake8 ../examples/ rstcheck README.rst deps = flake8 flake8-docstrings flake8-quotes rstcheck ================================================ FILE: library_c/CHANGELOG.txt ================================================ ================================================ FILE: library_c/MANIFEST.in ================================================ include README.md include README.txt include CHANGELOG.txt include setup.py include blinkt_wrap.c include blinkt.py include lib/* ================================================ FILE: library_c/Makefile ================================================ all: gcc -Wall -DTEST lib/blinkt.c -l bcm2835 -o blinkt devel: -rm -r build python setup.py build sudo python setup.py develop ================================================ FILE: library_c/README.md ================================================ ================================================ FILE: library_c/README.txt ================================================ ================================================ FILE: library_c/blinkt.i ================================================ %module blinkt %include "stdint.i" %include "carrays.i" %{ #include "lib/blinkt.h" %} %include "lib/blinkt.h" %pythoncode %{ import atexit def clean_exit(): stop() if start() > 0: raise ImportError("Blinkt requires root.") atexit.register(clean_exit) %} ================================================ FILE: library_c/blinkt.py ================================================ # This file was automatically generated by SWIG (http://www.swig.org). # Version 3.0.2 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info if version_info >= (2,6,0): def swig_import_helper(): from os.path import dirname import imp fp = None try: fp, pathname, description = imp.find_module('_blinkt', [dirname(__file__)]) except ImportError: import _blinkt return _blinkt if fp is not None: try: _mod = imp.load_module('_blinkt', fp, pathname, description) finally: fp.close() return _mod _blinkt = swig_import_helper() del swig_import_helper else: import _blinkt del version_info try: _swig_property = property except NameError: pass # Python < 2.2 doesn't have 'property'. def _swig_setattr_nondynamic(self,class_type,name,value,static=1): if (name == "thisown"): return self.this.own(value) if (name == "this"): if type(value).__name__ == 'SwigPyObject': self.__dict__[name] = value return method = class_type.__swig_setmethods__.get(name,None) if method: return method(self,value) if (not static): self.__dict__[name] = value else: raise AttributeError("You cannot add attributes to %s" % self) def _swig_setattr(self,class_type,name,value): return _swig_setattr_nondynamic(self,class_type,name,value,0) def _swig_getattr(self,class_type,name): if (name == "thisown"): return self.this.own() method = class_type.__swig_getmethods__.get(name,None) if method: return method(self) raise AttributeError(name) def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) try: _object = object _newclass = 1 except AttributeError: class _object : pass _newclass = 0 def clear(): return _blinkt.clear() clear = _blinkt.clear def set_pixel_uint32(*args): return _blinkt.set_pixel_uint32(*args) set_pixel_uint32 = _blinkt.set_pixel_uint32 def set_pixel(*args): return _blinkt.set_pixel(*args) set_pixel = _blinkt.set_pixel def set_pixel_brightness(*args): return _blinkt.set_pixel_brightness(*args) set_pixel_brightness = _blinkt.set_pixel_brightness def rgbb(*args): return _blinkt.rgbb(*args) rgbb = _blinkt.rgbb def rgb(*args): return _blinkt.rgb(*args) rgb = _blinkt.rgb def stop(): return _blinkt.stop() stop = _blinkt.stop def start(): return _blinkt.start() start = _blinkt.start def show(): return _blinkt.show() show = _blinkt.show import atexit def clean_exit(): stop() if start() > 0: raise ImportError("Blinkt requires root.") atexit.register(clean_exit) # This file is compatible with both classic and new-style classes. ================================================ FILE: library_c/blinkt_wrap.c ================================================ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 3.0.2 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make * changes to this file unless you know what you are doing--modify the SWIG * interface file instead. * ----------------------------------------------------------------------------- */ #define SWIGPYTHON #define SWIG_PYTHON_DIRECTOR_NO_VTABLE /* ----------------------------------------------------------------------------- * This section contains generic SWIG labels for method/variable * declarations/attributes, and other compiler dependent labels. * ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */ #ifndef SWIGTEMPLATEDISAMBIGUATOR # if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # elif defined(__HP_aCC) /* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ /* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ # define SWIGTEMPLATEDISAMBIGUATOR template # else # define SWIGTEMPLATEDISAMBIGUATOR # endif #endif /* inline attribute */ #ifndef SWIGINLINE # if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) # define SWIGINLINE inline # else # define SWIGINLINE # endif #endif /* attribute recognised by some compilers to avoid 'unused' warnings */ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif #endif #ifndef SWIG_MSC_UNSUPPRESS_4505 # if defined(_MSC_VER) # pragma warning(disable : 4505) /* unreferenced local function has been removed */ # endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else # define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif /* internal SWIG method */ #ifndef SWIGINTERN # define SWIGINTERN static SWIGUNUSED #endif /* internal inline SWIG method */ #ifndef SWIGINTERNINLINE # define SWIGINTERNINLINE SWIGINTERN SWIGINLINE #endif /* exporting methods */ #if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) # ifndef GCC_HASCLASSVISIBILITY # define GCC_HASCLASSVISIBILITY # endif #endif #ifndef SWIGEXPORT # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # if defined(STATIC_LINKED) # define SWIGEXPORT # else # define SWIGEXPORT __declspec(dllexport) # endif # else # if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) # define SWIGEXPORT __attribute__ ((visibility("default"))) # else # define SWIGEXPORT # endif # endif #endif /* calling conventions for Windows */ #ifndef SWIGSTDCALL # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL # endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ #if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) # define _CRT_SECURE_NO_DEPRECATE #endif /* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ #if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) # define _SCL_SECURE_NO_DEPRECATE #endif #if defined(_DEBUG) && defined(SWIG_PYTHON_INTERPRETER_NO_DEBUG) /* Use debug wrappers with the Python release dll */ # undef _DEBUG # include # define _DEBUG #else # include #endif /* ----------------------------------------------------------------------------- * swigrun.swg * * This file contains generic C API SWIG runtime support for pointer * type checking. * ----------------------------------------------------------------------------- */ /* This should only be incremented when either the layout of swig_type_info changes, or for whatever reason, the runtime changes incompatibly */ #define SWIG_RUNTIME_VERSION "4" /* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ #ifdef SWIG_TYPE_TABLE # define SWIG_QUOTE_STRING(x) #x # define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) # define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) #else # define SWIG_TYPE_TABLE_NAME #endif /* You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for creating a static or dynamic library from the SWIG runtime code. In 99.9% of the cases, SWIG just needs to declare them as 'static'. But only do this if strictly necessary, ie, if you have problems with your compiler or suchlike. */ #ifndef SWIGRUNTIME # define SWIGRUNTIME SWIGINTERN #endif #ifndef SWIGRUNTIMEINLINE # define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE #endif /* Generic buffer size */ #ifndef SWIG_BUFFER_SIZE # define SWIG_BUFFER_SIZE 1024 #endif /* Flags for pointer conversions */ #define SWIG_POINTER_DISOWN 0x1 #define SWIG_CAST_NEW_MEMORY 0x2 /* Flags for new pointer objects */ #define SWIG_POINTER_OWN 0x1 /* Flags/methods for returning states. The SWIG conversion methods, as ConvertPtr, return an integer that tells if the conversion was successful or not. And if not, an error code can be returned (see swigerrors.swg for the codes). Use the following macros/flags to set or process the returning states. In old versions of SWIG, code such as the following was usually written: if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { // success code } else { //fail code } Now you can be more explicit: int res = SWIG_ConvertPtr(obj,vptr,ty.flags); if (SWIG_IsOK(res)) { // success code } else { // fail code } which is the same really, but now you can also do Type *ptr; int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); if (SWIG_IsOK(res)) { // success code if (SWIG_IsNewObj(res) { ... delete *ptr; } else { ... } } else { // fail code } I.e., now SWIG_ConvertPtr can return new objects and you can identify the case and take care of the deallocation. Of course that also requires SWIG_ConvertPtr to return new result values, such as int SWIG_ConvertPtr(obj, ptr,...) { if () { if () { *ptr = ; return SWIG_NEWOBJ; } else { *ptr = ; return SWIG_OLDOBJ; } } else { return SWIG_BADOBJ; } } Of course, returning the plain '0(success)/-1(fail)' still works, but you can be more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the SWIG errors code. Finally, if the SWIG_CASTRANK_MODE is enabled, the result code allows to return the 'cast rank', for example, if you have this int food(double) int fooi(int); and you call food(1) // cast rank '1' (1 -> 1.0) fooi(1) // cast rank '0' just use the SWIG_AddCast()/SWIG_CheckState() */ #define SWIG_OK (0) #define SWIG_ERROR (-1) #define SWIG_IsOK(r) (r >= 0) #define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) /* The CastRankLimit says how many bits are used for the cast rank */ #define SWIG_CASTRANKLIMIT (1 << 8) /* The NewMask denotes the object was created (using new/malloc) */ #define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) /* The TmpMask is for in/out typemaps that use temporal objects */ #define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) /* Simple returning values */ #define SWIG_BADOBJ (SWIG_ERROR) #define SWIG_OLDOBJ (SWIG_OK) #define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) #define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) /* Check, add and del mask methods */ #define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) #define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) #define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) #define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) #define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) #define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) /* Cast-Rank Mode */ #if defined(SWIG_CASTRANK_MODE) # ifndef SWIG_TypeRank # define SWIG_TypeRank unsigned long # endif # ifndef SWIG_MAXCASTRANK /* Default cast allowed */ # define SWIG_MAXCASTRANK (2) # endif # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast(r) (r) # define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) #endif #include #ifdef __cplusplus extern "C" { #endif typedef void *(*swig_converter_func)(void *, int *); typedef struct swig_type_info *(*swig_dycast_func)(void **); /* Structure to store information on one type */ typedef struct swig_type_info { const char *name; /* mangled name of this type */ const char *str; /* human readable name of this type */ swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ struct swig_cast_info *cast; /* linked list of types that can cast into this type */ void *clientdata; /* language specific type data */ int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { swig_type_info *type; /* pointer to type that is equivalent to this type */ swig_converter_func converter; /* function to cast the void pointers */ struct swig_cast_info *next; /* pointer to next cast in linked list */ struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ size_t size; /* Number of types in this module */ struct swig_module_info *next; /* Pointer to next element in circularly linked list */ swig_type_info **type_initial; /* Array of initially generated type structures */ swig_cast_info **cast_initial; /* Array of initially generated casting structures */ void *clientdata; /* Language specific module data */ } swig_module_info; /* Compare two type names skipping the space characters, therefore "char*" == "char *" and "Class" == "Class", etc. Return 0 when the two name types are equivalent, as in strncmp, but skipping ' '. */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, const char *f2, const char *l2) { for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { while ((*f1 == ' ') && (f1 != l1)) ++f1; while ((*f2 == ' ') && (f2 != l2)) ++f2; if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; } return (int)((l1 - f1) - (l2 - f2)); } /* Check type equivalence in a name list like ||... Return 0 if equal, -1 if nb < tb, 1 if nb > tb */ SWIGRUNTIME int SWIG_TypeCmp(const char *nb, const char *tb) { int equiv = 1; const char* te = tb + strlen(tb); const char* ne = nb; while (equiv != 0 && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = SWIG_TypeNameComp(nb, ne, tb, te); if (*ne) ++ne; } return equiv; } /* Check type equivalence in a name list like ||... Return 0 if not equal, 1 if equal */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; } /* Check the typename */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { if (ty) { swig_cast_info *iter = ty->cast; while (iter) { if (strcmp(iter->type->name, c) == 0) { if (iter == ty->cast) return iter; /* Move iter to the top of the linked list */ iter->prev->next = iter->next; if (iter->next) iter->next->prev = iter->prev; iter->next = ty->cast; iter->prev = 0; if (ty->cast) ty->cast->prev = iter; ty->cast = iter; return iter; } iter = iter->next; } } return 0; } /* Identical to SWIG_TypeCheck, except strcmp is replaced with a pointer comparison */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *ty) { if (ty) { swig_cast_info *iter = ty->cast; while (iter) { if (iter->type == from) { if (iter == ty->cast) return iter; /* Move iter to the top of the linked list */ iter->prev->next = iter->next; if (iter->next) iter->next->prev = iter->prev; iter->next = ty->cast; iter->prev = 0; if (ty->cast) ty->cast->prev = iter; ty->cast = iter; return iter; } iter = iter->next; } } return 0; } /* Cast a pointer up an inheritance hierarchy */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } /* Dynamic pointer casting. Down an inheritance hierarchy */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { swig_type_info *lastty = ty; if (!ty || !ty->dcast) return ty; while (ty && (ty->dcast)) { ty = (*ty->dcast)(ptr); if (ty) lastty = ty; } return lastty; } /* Return the name associated with this type */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { return ty->name; } /* Return the pretty name associated with this type, that is an unmangled type name in a form presentable to the user. */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { /* The "str" field contains the equivalent pretty names of the type, separated by vertical-bar characters. We choose to print the last name, as it is often (?) the most specific. */ if (!type) return NULL; if (type->str != NULL) { const char *last_name = type->str; const char *s; for (s = type->str; *s; s++) if (*s == '|') last_name = s+1; return last_name; } else return type->name; } /* Set the clientdata field for a type */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { swig_cast_info *cast = ti->cast; /* if (ti->clientdata == clientdata) return; */ ti->clientdata = clientdata; while (cast) { if (!cast->converter) { swig_type_info *tc = cast->type; if (!tc->clientdata) { SWIG_TypeClientData(tc, clientdata); } } cast = cast->next; } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIG_TypeClientData(ti, clientdata); ti->owndata = 1; } /* Search for a swig_type_info structure only by mangled name Search is a O(log #types) We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { swig_module_info *iter = start; do { if (iter->size) { size_t l = 0; size_t r = iter->size - 1; do { /* since l+r >= 0, we can (>> 1) instead (/ 2) */ size_t i = (l + r) >> 1; const char *iname = iter->types[i]->name; if (iname) { int compare = strcmp(name, iname); if (compare == 0) { return iter->types[i]; } else if (compare < 0) { if (i) { r = i - 1; } else { break; } } else if (compare > 0) { l = i + 1; } } else { break; /* should never happen */ } } while (l <= r); } iter = iter->next; } while (iter != end); return 0; } /* Search for a swig_type_info structure for either a mangled name or a human readable name. It first searches the mangled names of the types, which is a O(log #types) If a type is not found it then searches the human readable names, which is O(#types). We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { /* STEP 1: Search the name field using binary search */ swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); if (ret) { return ret; } else { /* STEP 2: If the type hasn't been found, do a complete search of the str field (the human readable name) */ swig_module_info *iter = start; do { size_t i = 0; for (; i < iter->size; ++i) { if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) return iter->types[i]; } iter = iter->next; } while (iter != end); } /* neither found a match */ return 0; } /* Pack binary data into a string */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { static const char hex[17] = "0123456789abcdef"; const unsigned char *u = (unsigned char *) ptr; const unsigned char *eu = u + sz; for (; u != eu; ++u) { unsigned char uu = *u; *(c++) = hex[(uu & 0xf0) >> 4]; *(c++) = hex[uu & 0xf]; } return c; } /* Unpack binary data from a string */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { unsigned char *u = (unsigned char *) ptr; const unsigned char *eu = u + sz; for (; u != eu; ++u) { char d = *(c++); unsigned char uu; if ((d >= '0') && (d <= '9')) uu = ((d - '0') << 4); else if ((d >= 'a') && (d <= 'f')) uu = ((d - ('a'-10)) << 4); else return (char *) 0; d = *(c++); if ((d >= '0') && (d <= '9')) uu |= (d - '0'); else if ((d >= 'a') && (d <= 'f')) uu |= (d - ('a'-10)); else return (char *) 0; *u = uu; } return c; } /* Pack 'void *' into a string buffer. */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { char *r = buff; if ((2*sizeof(void *) + 2) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,&ptr,sizeof(void *)); if (strlen(name) + 1 > (bsz - (r - buff))) return 0; strcpy(r,name); return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { *ptr = (void *) 0; return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { char *r = buff; size_t lname = (name ? strlen(name) : 0); if ((2*sz + 2 + lname) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,ptr,sz); if (lname) { strncpy(r,name,lname+1); } else { *r = 0; } return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { memset(ptr,0,sz); return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sz); } #ifdef __cplusplus } #endif /* Errors in SWIG */ #define SWIG_UnknownError -1 #define SWIG_IOError -2 #define SWIG_RuntimeError -3 #define SWIG_IndexError -4 #define SWIG_TypeError -5 #define SWIG_DivisionByZero -6 #define SWIG_OverflowError -7 #define SWIG_SyntaxError -8 #define SWIG_ValueError -9 #define SWIG_SystemError -10 #define SWIG_AttributeError -11 #define SWIG_MemoryError -12 #define SWIG_NullReferenceError -13 /* Compatibility macros for Python 3 */ #if PY_VERSION_HEX >= 0x03000000 #define PyClass_Check(obj) PyObject_IsInstance(obj, (PyObject *)&PyType_Type) #define PyInt_Check(x) PyLong_Check(x) #define PyInt_AsLong(x) PyLong_AsLong(x) #define PyInt_FromLong(x) PyLong_FromLong(x) #define PyInt_FromSize_t(x) PyLong_FromSize_t(x) #define PyString_Check(name) PyBytes_Check(name) #define PyString_FromString(x) PyUnicode_FromString(x) #define PyString_Format(fmt, args) PyUnicode_Format(fmt, args) #define PyString_AsString(str) PyBytes_AsString(str) #define PyString_Size(str) PyBytes_Size(str) #define PyString_InternFromString(key) PyUnicode_InternFromString(key) #define Py_TPFLAGS_HAVE_CLASS Py_TPFLAGS_BASETYPE #define PyString_AS_STRING(x) PyUnicode_AS_STRING(x) #define _PyLong_FromSsize_t(x) PyLong_FromSsize_t(x) #endif #ifndef Py_TYPE # define Py_TYPE(op) ((op)->ob_type) #endif /* SWIG APIs for compatibility of both Python 2 & 3 */ #if PY_VERSION_HEX >= 0x03000000 # define SWIG_Python_str_FromFormat PyUnicode_FromFormat #else # define SWIG_Python_str_FromFormat PyString_FromFormat #endif /* Warning: This function will allocate a new string in Python 3, * so please call SWIG_Python_str_DelForPy3(x) to free the space. */ SWIGINTERN char* SWIG_Python_str_AsChar(PyObject *str) { #if PY_VERSION_HEX >= 0x03000000 char *cstr; char *newstr; Py_ssize_t len; str = PyUnicode_AsUTF8String(str); PyBytes_AsStringAndSize(str, &cstr, &len); newstr = (char *) malloc(len+1); memcpy(newstr, cstr, len+1); Py_XDECREF(str); return newstr; #else return PyString_AsString(str); #endif } #if PY_VERSION_HEX >= 0x03000000 # define SWIG_Python_str_DelForPy3(x) free( (void*) (x) ) #else # define SWIG_Python_str_DelForPy3(x) #endif SWIGINTERN PyObject* SWIG_Python_str_FromChar(const char *c) { #if PY_VERSION_HEX >= 0x03000000 return PyUnicode_FromString(c); #else return PyString_FromString(c); #endif } /* Add PyOS_snprintf for old Pythons */ #if PY_VERSION_HEX < 0x02020000 # if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM) # define PyOS_snprintf _snprintf # else # define PyOS_snprintf snprintf # endif #endif /* A crude PyString_FromFormat implementation for old Pythons */ #if PY_VERSION_HEX < 0x02020000 #ifndef SWIG_PYBUFFER_SIZE # define SWIG_PYBUFFER_SIZE 1024 #endif static PyObject * PyString_FromFormat(const char *fmt, ...) { va_list ap; char buf[SWIG_PYBUFFER_SIZE * 2]; int res; va_start(ap, fmt); res = vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf); } #endif /* Add PyObject_Del for old Pythons */ #if PY_VERSION_HEX < 0x01060000 # define PyObject_Del(op) PyMem_DEL((op)) #endif #ifndef PyObject_DEL # define PyObject_DEL PyObject_Del #endif /* A crude PyExc_StopIteration exception for old Pythons */ #if PY_VERSION_HEX < 0x02020000 # ifndef PyExc_StopIteration # define PyExc_StopIteration PyExc_RuntimeError # endif # ifndef PyObject_GenericGetAttr # define PyObject_GenericGetAttr 0 # endif #endif /* Py_NotImplemented is defined in 2.1 and up. */ #if PY_VERSION_HEX < 0x02010000 # ifndef Py_NotImplemented # define Py_NotImplemented PyExc_RuntimeError # endif #endif /* A crude PyString_AsStringAndSize implementation for old Pythons */ #if PY_VERSION_HEX < 0x02010000 # ifndef PyString_AsStringAndSize # define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;} # endif #endif /* PySequence_Size for old Pythons */ #if PY_VERSION_HEX < 0x02000000 # ifndef PySequence_Size # define PySequence_Size PySequence_Length # endif #endif /* PyBool_FromLong for old Pythons */ #if PY_VERSION_HEX < 0x02030000 static PyObject *PyBool_FromLong(long ok) { PyObject *result = ok ? Py_True : Py_False; Py_INCREF(result); return result; } #endif /* Py_ssize_t for old Pythons */ /* This code is as recommended by: */ /* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */ #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) typedef int Py_ssize_t; # define PY_SSIZE_T_MAX INT_MAX # define PY_SSIZE_T_MIN INT_MIN typedef inquiry lenfunc; typedef intargfunc ssizeargfunc; typedef intintargfunc ssizessizeargfunc; typedef intobjargproc ssizeobjargproc; typedef intintobjargproc ssizessizeobjargproc; typedef getreadbufferproc readbufferproc; typedef getwritebufferproc writebufferproc; typedef getsegcountproc segcountproc; typedef getcharbufferproc charbufferproc; static long PyNumber_AsSsize_t (PyObject *x, void *SWIGUNUSEDPARM(exc)) { long result = 0; PyObject *i = PyNumber_Int(x); if (i) { result = PyInt_AsLong(i); Py_DECREF(i); } return result; } #endif #if PY_VERSION_HEX < 0x02050000 #define PyInt_FromSize_t(x) PyInt_FromLong((long)x) #endif #if PY_VERSION_HEX < 0x02040000 #define Py_VISIT(op) \ do { \ if (op) { \ int vret = visit((op), arg); \ if (vret) \ return vret; \ } \ } while (0) #endif #if PY_VERSION_HEX < 0x02030000 typedef struct { PyTypeObject type; PyNumberMethods as_number; PyMappingMethods as_mapping; PySequenceMethods as_sequence; PyBufferProcs as_buffer; PyObject *name, *slots; } PyHeapTypeObject; #endif #if PY_VERSION_HEX < 0x02030000 typedef destructor freefunc; #endif #if ((PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION > 6) || \ (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION > 0) || \ (PY_MAJOR_VERSION > 3)) # define SWIGPY_USE_CAPSULE # define SWIGPY_CAPSULE_NAME ((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION ".type_pointer_capsule" SWIG_TYPE_TABLE_NAME) #endif #if PY_VERSION_HEX < 0x03020000 #define PyDescr_TYPE(x) (((PyDescrObject *)(x))->d_type) #define PyDescr_NAME(x) (((PyDescrObject *)(x))->d_name) #endif /* ----------------------------------------------------------------------------- * error manipulation * ----------------------------------------------------------------------------- */ SWIGRUNTIME PyObject* SWIG_Python_ErrorType(int code) { PyObject* type = 0; switch(code) { case SWIG_MemoryError: type = PyExc_MemoryError; break; case SWIG_IOError: type = PyExc_IOError; break; case SWIG_RuntimeError: type = PyExc_RuntimeError; break; case SWIG_IndexError: type = PyExc_IndexError; break; case SWIG_TypeError: type = PyExc_TypeError; break; case SWIG_DivisionByZero: type = PyExc_ZeroDivisionError; break; case SWIG_OverflowError: type = PyExc_OverflowError; break; case SWIG_SyntaxError: type = PyExc_SyntaxError; break; case SWIG_ValueError: type = PyExc_ValueError; break; case SWIG_SystemError: type = PyExc_SystemError; break; case SWIG_AttributeError: type = PyExc_AttributeError; break; default: type = PyExc_RuntimeError; } return type; } SWIGRUNTIME void SWIG_Python_AddErrorMsg(const char* mesg) { PyObject *type = 0; PyObject *value = 0; PyObject *traceback = 0; if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback); if (value) { char *tmp; PyObject *old_str = PyObject_Str(value); PyErr_Clear(); Py_XINCREF(type); PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); SWIG_Python_str_DelForPy3(tmp); Py_DECREF(old_str); Py_DECREF(value); } else { PyErr_SetString(PyExc_RuntimeError, mesg); } } #if defined(SWIG_PYTHON_NO_THREADS) # if defined(SWIG_PYTHON_THREADS) # undef SWIG_PYTHON_THREADS # endif #endif #if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */ # if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL) # if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */ # define SWIG_PYTHON_USE_GIL # endif # endif # if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */ # ifndef SWIG_PYTHON_INITIALIZE_THREADS # define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads() # endif # ifdef __cplusplus /* C++ code */ class SWIG_Python_Thread_Block { bool status; PyGILState_STATE state; public: void end() { if (status) { PyGILState_Release(state); status = false;} } SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} ~SWIG_Python_Thread_Block() { end(); } }; class SWIG_Python_Thread_Allow { bool status; PyThreadState *save; public: void end() { if (status) { PyEval_RestoreThread(save); status = false; }} SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} ~SWIG_Python_Thread_Allow() { end(); } }; # define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block # define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() # define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow # define SWIG_PYTHON_THREAD_END_ALLOW _swig_thread_allow.end() # else /* C code */ # define SWIG_PYTHON_THREAD_BEGIN_BLOCK PyGILState_STATE _swig_thread_block = PyGILState_Ensure() # define SWIG_PYTHON_THREAD_END_BLOCK PyGILState_Release(_swig_thread_block) # define SWIG_PYTHON_THREAD_BEGIN_ALLOW PyThreadState *_swig_thread_allow = PyEval_SaveThread() # define SWIG_PYTHON_THREAD_END_ALLOW PyEval_RestoreThread(_swig_thread_allow) # endif # else /* Old thread way, not implemented, user must provide it */ # if !defined(SWIG_PYTHON_INITIALIZE_THREADS) # define SWIG_PYTHON_INITIALIZE_THREADS # endif # if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK) # define SWIG_PYTHON_THREAD_BEGIN_BLOCK # endif # if !defined(SWIG_PYTHON_THREAD_END_BLOCK) # define SWIG_PYTHON_THREAD_END_BLOCK # endif # if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW) # define SWIG_PYTHON_THREAD_BEGIN_ALLOW # endif # if !defined(SWIG_PYTHON_THREAD_END_ALLOW) # define SWIG_PYTHON_THREAD_END_ALLOW # endif # endif #else /* No thread support */ # define SWIG_PYTHON_INITIALIZE_THREADS # define SWIG_PYTHON_THREAD_BEGIN_BLOCK # define SWIG_PYTHON_THREAD_END_BLOCK # define SWIG_PYTHON_THREAD_BEGIN_ALLOW # define SWIG_PYTHON_THREAD_END_ALLOW #endif /* ----------------------------------------------------------------------------- * Python API portion that goes into the runtime * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #endif /* ----------------------------------------------------------------------------- * Constant declarations * ----------------------------------------------------------------------------- */ /* Constant Types */ #define SWIG_PY_POINTER 4 #define SWIG_PY_BINARY 5 /* Constant information structure */ typedef struct swig_const_info { int type; char *name; long lvalue; double dvalue; void *pvalue; swig_type_info **ptype; } swig_const_info; /* ----------------------------------------------------------------------------- * Wrapper of PyInstanceMethod_New() used in Python 3 * It is exported to the generated module, used for -fastproxy * ----------------------------------------------------------------------------- */ #if PY_VERSION_HEX >= 0x03000000 SWIGRUNTIME PyObject* SWIG_PyInstanceMethod_New(PyObject *SWIGUNUSEDPARM(self), PyObject *func) { return PyInstanceMethod_New(func); } #else SWIGRUNTIME PyObject* SWIG_PyInstanceMethod_New(PyObject *SWIGUNUSEDPARM(self), PyObject *SWIGUNUSEDPARM(func)) { return NULL; } #endif #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * pyrun.swg * * This file contains the runtime support for Python modules * and includes code for managing global variables and pointer * type checking. * * ----------------------------------------------------------------------------- */ /* Common SWIG API */ /* for raw pointers */ #define SWIG_Python_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0) #define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtr(obj, pptr, type, flags) #define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own) #ifdef SWIGPYTHON_BUILTIN #define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(self, ptr, type, flags) #else #define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(NULL, ptr, type, flags) #endif #define SWIG_InternalNewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(NULL, ptr, type, flags) #define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) #define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) #define swig_owntype int /* for raw packed data */ #define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) #define SWIG_NewPackedObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) /* for class or struct pointers */ #define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags) #define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags) /* for C or C++ function pointers */ #define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_Python_ConvertFunctionPtr(obj, pptr, type) #define SWIG_NewFunctionPtrObj(ptr, type) SWIG_Python_NewPointerObj(NULL, ptr, type, 0) /* for C++ member pointers, ie, member methods */ #define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) #define SWIG_NewMemberObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) /* Runtime API */ #define SWIG_GetModule(clientdata) SWIG_Python_GetModule(clientdata) #define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) #define SWIG_NewClientData(obj) SwigPyClientData_New(obj) #define SWIG_SetErrorObj SWIG_Python_SetErrorObj #define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg #define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) #define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) #define SWIG_fail goto fail /* Runtime API implementation */ /* Error manipulation */ SWIGINTERN void SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; PyErr_SetObject(errtype, obj); Py_DECREF(obj); SWIG_PYTHON_THREAD_END_BLOCK; } SWIGINTERN void SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; PyErr_SetString(errtype, msg); SWIG_PYTHON_THREAD_END_BLOCK; } #define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) /* Set a constant value */ #if defined(SWIGPYTHON_BUILTIN) SWIGINTERN void SwigPyBuiltin_AddPublicSymbol(PyObject *seq, const char *key) { PyObject *s = PyString_InternFromString(key); PyList_Append(seq, s); Py_DECREF(s); } SWIGINTERN void SWIG_Python_SetConstant(PyObject *d, PyObject *public_interface, const char *name, PyObject *obj) { #if PY_VERSION_HEX < 0x02030000 PyDict_SetItemString(d, (char *)name, obj); #else PyDict_SetItemString(d, name, obj); #endif Py_DECREF(obj); if (public_interface) SwigPyBuiltin_AddPublicSymbol(public_interface, name); } #else SWIGINTERN void SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { #if PY_VERSION_HEX < 0x02030000 PyDict_SetItemString(d, (char *)name, obj); #else PyDict_SetItemString(d, name, obj); #endif Py_DECREF(obj); } #endif /* Append a value to the result obj */ SWIGINTERN PyObject* SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { #if !defined(SWIG_PYTHON_OUTPUT_TUPLE) if (!result) { result = obj; } else if (result == Py_None) { Py_DECREF(result); result = obj; } else { if (!PyList_Check(result)) { PyObject *o2 = result; result = PyList_New(1); PyList_SetItem(result, 0, o2); } PyList_Append(result,obj); Py_DECREF(obj); } return result; #else PyObject* o2; PyObject* o3; if (!result) { result = obj; } else if (result == Py_None) { Py_DECREF(result); result = obj; } else { if (!PyTuple_Check(result)) { o2 = result; result = PyTuple_New(1); PyTuple_SET_ITEM(result, 0, o2); } o3 = PyTuple_New(1); PyTuple_SET_ITEM(o3, 0, obj); o2 = result; result = PySequence_Concat(o2, o3); Py_DECREF(o2); Py_DECREF(o3); } return result; #endif } /* Unpack the argument tuple */ SWIGINTERN int SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) { if (!args) { if (!min && !max) { return 1; } else { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", name, (min == max ? "" : "at least "), (int)min); return 0; } } if (!PyTuple_Check(args)) { if (min <= 1 && max >= 1) { int i; objs[0] = args; for (i = 1; i < max; ++i) { objs[i] = 0; } return 2; } PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); return 0; } else { Py_ssize_t l = PyTuple_GET_SIZE(args); if (l < min) { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", name, (min == max ? "" : "at least "), (int)min, (int)l); return 0; } else if (l > max) { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", name, (min == max ? "" : "at most "), (int)max, (int)l); return 0; } else { int i; for (i = 0; i < l; ++i) { objs[i] = PyTuple_GET_ITEM(args, i); } for (; l < max; ++l) { objs[l] = 0; } return i + 1; } } } /* A functor is a function object with one single object argument */ #if PY_VERSION_HEX >= 0x02020000 #define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunctionObjArgs(functor, obj, NULL); #else #define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunction(functor, "O", obj); #endif /* Helper for static pointer initialization for both C and C++ code, for example static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...); */ #ifdef __cplusplus #define SWIG_STATIC_POINTER(var) var #else #define SWIG_STATIC_POINTER(var) var = 0; if (!var) var #endif /* ----------------------------------------------------------------------------- * Pointer declarations * ----------------------------------------------------------------------------- */ /* Flags for new pointer objects */ #define SWIG_POINTER_NOSHADOW (SWIG_POINTER_OWN << 1) #define SWIG_POINTER_NEW (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN) #define SWIG_POINTER_IMPLICIT_CONV (SWIG_POINTER_DISOWN << 1) #define SWIG_BUILTIN_TP_INIT (SWIG_POINTER_OWN << 2) #define SWIG_BUILTIN_INIT (SWIG_BUILTIN_TP_INIT | SWIG_POINTER_OWN) #ifdef __cplusplus extern "C" { #endif /* How to access Py_None */ #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # ifndef SWIG_PYTHON_NO_BUILD_NONE # ifndef SWIG_PYTHON_BUILD_NONE # define SWIG_PYTHON_BUILD_NONE # endif # endif #endif #ifdef SWIG_PYTHON_BUILD_NONE # ifdef Py_None # undef Py_None # define Py_None SWIG_Py_None() # endif SWIGRUNTIMEINLINE PyObject * _SWIG_Py_None(void) { PyObject *none = Py_BuildValue((char*)""); Py_DECREF(none); return none; } SWIGRUNTIME PyObject * SWIG_Py_None(void) { static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None(); return none; } #endif /* The python void return value */ SWIGRUNTIMEINLINE PyObject * SWIG_Py_Void(void) { PyObject *none = Py_None; Py_INCREF(none); return none; } /* SwigPyClientData */ typedef struct { PyObject *klass; PyObject *newraw; PyObject *newargs; PyObject *destroy; int delargs; int implicitconv; PyTypeObject *pytype; } SwigPyClientData; SWIGRUNTIMEINLINE int SWIG_Python_CheckImplicit(swig_type_info *ty) { SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; return data ? data->implicitconv : 0; } SWIGRUNTIMEINLINE PyObject * SWIG_Python_ExceptionType(swig_type_info *desc) { SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0; PyObject *klass = data ? data->klass : 0; return (klass ? klass : PyExc_RuntimeError); } SWIGRUNTIME SwigPyClientData * SwigPyClientData_New(PyObject* obj) { if (!obj) { return 0; } else { SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData)); /* the klass element */ data->klass = obj; Py_INCREF(data->klass); /* the newraw method and newargs arguments used to create a new raw instance */ if (PyClass_Check(obj)) { data->newraw = 0; data->newargs = obj; Py_INCREF(obj); } else { #if (PY_VERSION_HEX < 0x02020000) data->newraw = 0; #else data->newraw = PyObject_GetAttrString(data->klass, (char *)"__new__"); #endif if (data->newraw) { Py_INCREF(data->newraw); data->newargs = PyTuple_New(1); PyTuple_SetItem(data->newargs, 0, obj); } else { data->newargs = obj; } Py_INCREF(data->newargs); } /* the destroy method, aka as the C++ delete method */ data->destroy = PyObject_GetAttrString(data->klass, (char *)"__swig_destroy__"); if (PyErr_Occurred()) { PyErr_Clear(); data->destroy = 0; } if (data->destroy) { int flags; Py_INCREF(data->destroy); flags = PyCFunction_GET_FLAGS(data->destroy); #ifdef METH_O data->delargs = !(flags & (METH_O)); #else data->delargs = 0; #endif } else { data->delargs = 0; } data->implicitconv = 0; data->pytype = 0; return data; } } SWIGRUNTIME void SwigPyClientData_Del(SwigPyClientData *data) { Py_XDECREF(data->newraw); Py_XDECREF(data->newargs); Py_XDECREF(data->destroy); } /* =============== SwigPyObject =====================*/ typedef struct { PyObject_HEAD void *ptr; swig_type_info *ty; int own; PyObject *next; #ifdef SWIGPYTHON_BUILTIN PyObject *dict; #endif } SwigPyObject; SWIGRUNTIME PyObject * SwigPyObject_long(SwigPyObject *v) { return PyLong_FromVoidPtr(v->ptr); } SWIGRUNTIME PyObject * SwigPyObject_format(const char* fmt, SwigPyObject *v) { PyObject *res = NULL; PyObject *args = PyTuple_New(1); if (args) { if (PyTuple_SetItem(args, 0, SwigPyObject_long(v)) == 0) { PyObject *ofmt = SWIG_Python_str_FromChar(fmt); if (ofmt) { #if PY_VERSION_HEX >= 0x03000000 res = PyUnicode_Format(ofmt,args); #else res = PyString_Format(ofmt,args); #endif Py_DECREF(ofmt); } Py_DECREF(args); } } return res; } SWIGRUNTIME PyObject * SwigPyObject_oct(SwigPyObject *v) { return SwigPyObject_format("%o",v); } SWIGRUNTIME PyObject * SwigPyObject_hex(SwigPyObject *v) { return SwigPyObject_format("%x",v); } SWIGRUNTIME PyObject * #ifdef METH_NOARGS SwigPyObject_repr(SwigPyObject *v) #else SwigPyObject_repr(SwigPyObject *v, PyObject *args) #endif { const char *name = SWIG_TypePrettyName(v->ty); PyObject *repr = SWIG_Python_str_FromFormat("", (name ? name : "unknown"), (void *)v); if (v->next) { # ifdef METH_NOARGS PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); # else PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next, args); # endif # if PY_VERSION_HEX >= 0x03000000 PyObject *joined = PyUnicode_Concat(repr, nrep); Py_DecRef(repr); Py_DecRef(nrep); repr = joined; # else PyString_ConcatAndDel(&repr,nrep); # endif } return repr; } SWIGRUNTIME int SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w) { void *i = v->ptr; void *j = w->ptr; return (i < j) ? -1 : ((i > j) ? 1 : 0); } /* Added for Python 3.x, would it also be useful for Python 2.x? */ SWIGRUNTIME PyObject* SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op) { PyObject* res; if( op != Py_EQ && op != Py_NE ) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } res = PyBool_FromLong( (SwigPyObject_compare(v, w)==0) == (op == Py_EQ) ? 1 : 0); return res; } SWIGRUNTIME PyTypeObject* SwigPyObject_TypeOnce(void); #ifdef SWIGPYTHON_BUILTIN static swig_type_info *SwigPyObject_stype = 0; SWIGRUNTIME PyTypeObject* SwigPyObject_type(void) { SwigPyClientData *cd; assert(SwigPyObject_stype); cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; assert(cd); assert(cd->pytype); return cd->pytype; } #else SWIGRUNTIME PyTypeObject* SwigPyObject_type(void) { static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyObject_TypeOnce(); return type; } #endif SWIGRUNTIMEINLINE int SwigPyObject_Check(PyObject *op) { #ifdef SWIGPYTHON_BUILTIN PyTypeObject *target_tp = SwigPyObject_type(); if (PyType_IsSubtype(op->ob_type, target_tp)) return 1; return (strcmp(op->ob_type->tp_name, "SwigPyObject") == 0); #else return (Py_TYPE(op) == SwigPyObject_type()) || (strcmp(Py_TYPE(op)->tp_name,"SwigPyObject") == 0); #endif } SWIGRUNTIME PyObject * SwigPyObject_New(void *ptr, swig_type_info *ty, int own); SWIGRUNTIME void SwigPyObject_dealloc(PyObject *v) { SwigPyObject *sobj = (SwigPyObject *) v; PyObject *next = sobj->next; if (sobj->own == SWIG_POINTER_OWN) { swig_type_info *ty = sobj->ty; SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; PyObject *destroy = data ? data->destroy : 0; if (destroy) { /* destroy is always a VARARGS method */ PyObject *res; if (data->delargs) { /* we need to create a temporary object to carry the destroy operation */ PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); res = SWIG_Python_CallFunctor(destroy, tmp); Py_DECREF(tmp); } else { PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); PyObject *mself = PyCFunction_GET_SELF(destroy); res = ((*meth)(mself, v)); } Py_XDECREF(res); } #if !defined(SWIG_PYTHON_SILENT_MEMLEAK) else { const char *name = SWIG_TypePrettyName(ty); printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); } #endif } Py_XDECREF(next); PyObject_DEL(v); } SWIGRUNTIME PyObject* SwigPyObject_append(PyObject* v, PyObject* next) { SwigPyObject *sobj = (SwigPyObject *) v; #ifndef METH_O PyObject *tmp = 0; if (!PyArg_ParseTuple(next,(char *)"O:append", &tmp)) return NULL; next = tmp; #endif if (!SwigPyObject_Check(next)) { return NULL; } sobj->next = next; Py_INCREF(next); return SWIG_Py_Void(); } SWIGRUNTIME PyObject* #ifdef METH_NOARGS SwigPyObject_next(PyObject* v) #else SwigPyObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { SwigPyObject *sobj = (SwigPyObject *) v; if (sobj->next) { Py_INCREF(sobj->next); return sobj->next; } else { return SWIG_Py_Void(); } } SWIGINTERN PyObject* #ifdef METH_NOARGS SwigPyObject_disown(PyObject *v) #else SwigPyObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { SwigPyObject *sobj = (SwigPyObject *)v; sobj->own = 0; return SWIG_Py_Void(); } SWIGINTERN PyObject* #ifdef METH_NOARGS SwigPyObject_acquire(PyObject *v) #else SwigPyObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { SwigPyObject *sobj = (SwigPyObject *)v; sobj->own = SWIG_POINTER_OWN; return SWIG_Py_Void(); } SWIGINTERN PyObject* SwigPyObject_own(PyObject *v, PyObject *args) { PyObject *val = 0; #if (PY_VERSION_HEX < 0x02020000) if (!PyArg_ParseTuple(args,(char *)"|O:own",&val)) #elif (PY_VERSION_HEX < 0x02050000) if (!PyArg_UnpackTuple(args, (char *)"own", 0, 1, &val)) #else if (!PyArg_UnpackTuple(args, "own", 0, 1, &val)) #endif { return NULL; } else { SwigPyObject *sobj = (SwigPyObject *)v; PyObject *obj = PyBool_FromLong(sobj->own); if (val) { #ifdef METH_NOARGS if (PyObject_IsTrue(val)) { SwigPyObject_acquire(v); } else { SwigPyObject_disown(v); } #else if (PyObject_IsTrue(val)) { SwigPyObject_acquire(v,args); } else { SwigPyObject_disown(v,args); } #endif } return obj; } } #ifdef METH_O static PyMethodDef swigobject_methods[] = { {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_NOARGS, (char *)"releases ownership of the pointer"}, {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_NOARGS, (char *)"acquires ownership of the pointer"}, {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, {(char *)"append", (PyCFunction)SwigPyObject_append, METH_O, (char *)"appends another 'this' object"}, {(char *)"next", (PyCFunction)SwigPyObject_next, METH_NOARGS, (char *)"returns the next 'this' object"}, {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_NOARGS, (char *)"returns object representation"}, {0, 0, 0, 0} }; #else static PyMethodDef swigobject_methods[] = { {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_VARARGS, (char *)"releases ownership of the pointer"}, {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_VARARGS, (char *)"aquires ownership of the pointer"}, {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, {(char *)"append", (PyCFunction)SwigPyObject_append, METH_VARARGS, (char *)"appends another 'this' object"}, {(char *)"next", (PyCFunction)SwigPyObject_next, METH_VARARGS, (char *)"returns the next 'this' object"}, {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_VARARGS, (char *)"returns object representation"}, {0, 0, 0, 0} }; #endif #if PY_VERSION_HEX < 0x02020000 SWIGINTERN PyObject * SwigPyObject_getattr(SwigPyObject *sobj,char *name) { return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name); } #endif SWIGRUNTIME PyTypeObject* SwigPyObject_TypeOnce(void) { static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; static PyNumberMethods SwigPyObject_as_number = { (binaryfunc)0, /*nb_add*/ (binaryfunc)0, /*nb_subtract*/ (binaryfunc)0, /*nb_multiply*/ /* nb_divide removed in Python 3 */ #if PY_VERSION_HEX < 0x03000000 (binaryfunc)0, /*nb_divide*/ #endif (binaryfunc)0, /*nb_remainder*/ (binaryfunc)0, /*nb_divmod*/ (ternaryfunc)0,/*nb_power*/ (unaryfunc)0, /*nb_negative*/ (unaryfunc)0, /*nb_positive*/ (unaryfunc)0, /*nb_absolute*/ (inquiry)0, /*nb_nonzero*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ #if PY_VERSION_HEX < 0x03000000 0, /*nb_coerce*/ #endif (unaryfunc)SwigPyObject_long, /*nb_int*/ #if PY_VERSION_HEX < 0x03000000 (unaryfunc)SwigPyObject_long, /*nb_long*/ #else 0, /*nb_reserved*/ #endif (unaryfunc)0, /*nb_float*/ #if PY_VERSION_HEX < 0x03000000 (unaryfunc)SwigPyObject_oct, /*nb_oct*/ (unaryfunc)SwigPyObject_hex, /*nb_hex*/ #endif #if PY_VERSION_HEX >= 0x03000000 /* 3.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ #elif PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ #elif PY_VERSION_HEX >= 0x02020000 /* 2.2.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ #elif PY_VERSION_HEX >= 0x02000000 /* 2.0.0 */ 0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */ #endif }; static PyTypeObject swigpyobject_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX >= 0x03000000 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif (char *)"SwigPyObject", /* tp_name */ sizeof(SwigPyObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SwigPyObject_dealloc, /* tp_dealloc */ 0, /* tp_print */ #if PY_VERSION_HEX < 0x02020000 (getattrfunc)SwigPyObject_getattr, /* tp_getattr */ #else (getattrfunc)0, /* tp_getattr */ #endif (setattrfunc)0, /* tp_setattr */ #if PY_VERSION_HEX >= 0x03000000 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ #else (cmpfunc)SwigPyObject_compare, /* tp_compare */ #endif (reprfunc)SwigPyObject_repr, /* tp_repr */ &SwigPyObject_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ swigobject_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)SwigPyObject_richcompare,/* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0, /* tp_iter */ 0, /* tp_iternext */ swigobject_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #if PY_VERSION_HEX >= 0x02060000 0, /* tp_version */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; swigpyobject_type = tmp; type_init = 1; #if PY_VERSION_HEX < 0x02020000 swigpyobject_type.ob_type = &PyType_Type; #else if (PyType_Ready(&swigpyobject_type) < 0) return NULL; #endif } return &swigpyobject_type; } SWIGRUNTIME PyObject * SwigPyObject_New(void *ptr, swig_type_info *ty, int own) { SwigPyObject *sobj = PyObject_NEW(SwigPyObject, SwigPyObject_type()); if (sobj) { sobj->ptr = ptr; sobj->ty = ty; sobj->own = own; sobj->next = 0; } return (PyObject *)sobj; } /* ----------------------------------------------------------------------------- * Implements a simple Swig Packed type, and use it instead of string * ----------------------------------------------------------------------------- */ typedef struct { PyObject_HEAD void *pack; swig_type_info *ty; size_t size; } SwigPyPacked; SWIGRUNTIME int SwigPyPacked_print(SwigPyPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { char result[SWIG_BUFFER_SIZE]; fputs("pack, v->size, 0, sizeof(result))) { fputs("at ", fp); fputs(result, fp); } fputs(v->ty->name,fp); fputs(">", fp); return 0; } SWIGRUNTIME PyObject * SwigPyPacked_repr(SwigPyPacked *v) { char result[SWIG_BUFFER_SIZE]; if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { return SWIG_Python_str_FromFormat("", result, v->ty->name); } else { return SWIG_Python_str_FromFormat("", v->ty->name); } } SWIGRUNTIME PyObject * SwigPyPacked_str(SwigPyPacked *v) { char result[SWIG_BUFFER_SIZE]; if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name); } else { return SWIG_Python_str_FromChar(v->ty->name); } } SWIGRUNTIME int SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w) { size_t i = v->size; size_t j = w->size; int s = (i < j) ? -1 : ((i > j) ? 1 : 0); return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size); } SWIGRUNTIME PyTypeObject* SwigPyPacked_TypeOnce(void); SWIGRUNTIME PyTypeObject* SwigPyPacked_type(void) { static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyPacked_TypeOnce(); return type; } SWIGRUNTIMEINLINE int SwigPyPacked_Check(PyObject *op) { return ((op)->ob_type == SwigPyPacked_TypeOnce()) || (strcmp((op)->ob_type->tp_name,"SwigPyPacked") == 0); } SWIGRUNTIME void SwigPyPacked_dealloc(PyObject *v) { if (SwigPyPacked_Check(v)) { SwigPyPacked *sobj = (SwigPyPacked *) v; free(sobj->pack); } PyObject_DEL(v); } SWIGRUNTIME PyTypeObject* SwigPyPacked_TypeOnce(void) { static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; static PyTypeObject swigpypacked_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX>=0x03000000 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif (char *)"SwigPyPacked", /* tp_name */ sizeof(SwigPyPacked), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SwigPyPacked_dealloc, /* tp_dealloc */ (printfunc)SwigPyPacked_print, /* tp_print */ (getattrfunc)0, /* tp_getattr */ (setattrfunc)0, /* tp_setattr */ #if PY_VERSION_HEX>=0x03000000 0, /* tp_reserved in 3.0.1 */ #else (cmpfunc)SwigPyPacked_compare, /* tp_compare */ #endif (reprfunc)SwigPyPacked_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ (reprfunc)SwigPyPacked_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ swigpacked_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #if PY_VERSION_HEX >= 0x02060000 0, /* tp_version */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; swigpypacked_type = tmp; type_init = 1; #if PY_VERSION_HEX < 0x02020000 swigpypacked_type.ob_type = &PyType_Type; #else if (PyType_Ready(&swigpypacked_type) < 0) return NULL; #endif } return &swigpypacked_type; } SWIGRUNTIME PyObject * SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty) { SwigPyPacked *sobj = PyObject_NEW(SwigPyPacked, SwigPyPacked_type()); if (sobj) { void *pack = malloc(size); if (pack) { memcpy(pack, ptr, size); sobj->pack = pack; sobj->ty = ty; sobj->size = size; } else { PyObject_DEL((PyObject *) sobj); sobj = 0; } } return (PyObject *) sobj; } SWIGRUNTIME swig_type_info * SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) { if (SwigPyPacked_Check(obj)) { SwigPyPacked *sobj = (SwigPyPacked *)obj; if (sobj->size != size) return 0; memcpy(ptr, sobj->pack, size); return sobj->ty; } else { return 0; } } /* ----------------------------------------------------------------------------- * pointers/data manipulation * ----------------------------------------------------------------------------- */ SWIGRUNTIMEINLINE PyObject * _SWIG_This(void) { return SWIG_Python_str_FromChar("this"); } static PyObject *swig_this = NULL; SWIGRUNTIME PyObject * SWIG_This(void) { if (swig_this == NULL) swig_this = _SWIG_This(); return swig_this; } /* #define SWIG_PYTHON_SLOW_GETSET_THIS */ /* TODO: I don't know how to implement the fast getset in Python 3 right now */ #if PY_VERSION_HEX>=0x03000000 #define SWIG_PYTHON_SLOW_GETSET_THIS #endif SWIGRUNTIME SwigPyObject * SWIG_Python_GetSwigThis(PyObject *pyobj) { PyObject *obj; if (SwigPyObject_Check(pyobj)) return (SwigPyObject *) pyobj; #ifdef SWIGPYTHON_BUILTIN (void)obj; # ifdef PyWeakref_CheckProxy if (PyWeakref_CheckProxy(pyobj)) { pyobj = PyWeakref_GET_OBJECT(pyobj); if (pyobj && SwigPyObject_Check(pyobj)) return (SwigPyObject*) pyobj; } # endif return NULL; #else obj = 0; #if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000)) if (PyInstance_Check(pyobj)) { obj = _PyInstance_Lookup(pyobj, SWIG_This()); } else { PyObject **dictptr = _PyObject_GetDictPtr(pyobj); if (dictptr != NULL) { PyObject *dict = *dictptr; obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; } else { #ifdef PyWeakref_CheckProxy if (PyWeakref_CheckProxy(pyobj)) { PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; } #endif obj = PyObject_GetAttr(pyobj,SWIG_This()); if (obj) { Py_DECREF(obj); } else { if (PyErr_Occurred()) PyErr_Clear(); return 0; } } } #else obj = PyObject_GetAttr(pyobj,SWIG_This()); if (obj) { Py_DECREF(obj); } else { if (PyErr_Occurred()) PyErr_Clear(); return 0; } #endif if (obj && !SwigPyObject_Check(obj)) { /* a PyObject is called 'this', try to get the 'real this' SwigPyObject from it */ return SWIG_Python_GetSwigThis(obj); } return (SwigPyObject *)obj; #endif } /* Acquire a pointer value */ SWIGRUNTIME int SWIG_Python_AcquirePtr(PyObject *obj, int own) { if (own == SWIG_POINTER_OWN) { SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); if (sobj) { int oldown = sobj->own; sobj->own = own; return oldown; } } return 0; } /* Convert a pointer value */ SWIGRUNTIME int SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { int res; SwigPyObject *sobj; int implicit_conv = (flags & SWIG_POINTER_IMPLICIT_CONV) != 0; if (!obj) return SWIG_ERROR; if (obj == Py_None && !implicit_conv) { if (ptr) *ptr = 0; return SWIG_OK; } res = SWIG_ERROR; sobj = SWIG_Python_GetSwigThis(obj); if (own) *own = 0; while (sobj) { void *vptr = sobj->ptr; if (ty) { swig_type_info *to = sobj->ty; if (to == ty) { /* no type cast needed */ if (ptr) *ptr = vptr; break; } else { swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); if (!tc) { sobj = (SwigPyObject *)sobj->next; } else { if (ptr) { int newmemory = 0; *ptr = SWIG_TypeCast(tc,vptr,&newmemory); if (newmemory == SWIG_CAST_NEW_MEMORY) { assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */ if (own) *own = *own | SWIG_CAST_NEW_MEMORY; } } break; } } } else { if (ptr) *ptr = vptr; break; } } if (sobj) { if (own) *own = *own | sobj->own; if (flags & SWIG_POINTER_DISOWN) { sobj->own = 0; } res = SWIG_OK; } else { if (implicit_conv) { SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; if (data && !data->implicitconv) { PyObject *klass = data->klass; if (klass) { PyObject *impconv; data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ impconv = SWIG_Python_CallFunctor(klass, obj); data->implicitconv = 0; if (PyErr_Occurred()) { PyErr_Clear(); impconv = 0; } if (impconv) { SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv); if (iobj) { void *vptr; res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); if (SWIG_IsOK(res)) { if (ptr) { *ptr = vptr; /* transfer the ownership to 'ptr' */ iobj->own = 0; res = SWIG_AddCast(res); res = SWIG_AddNewMask(res); } else { res = SWIG_AddCast(res); } } } Py_DECREF(impconv); } } } } if (!SWIG_IsOK(res) && obj == Py_None) { if (ptr) *ptr = 0; if (PyErr_Occurred()) PyErr_Clear(); res = SWIG_OK; } } return res; } /* Convert a function ptr value */ SWIGRUNTIME int SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { if (!PyCFunction_Check(obj)) { return SWIG_ConvertPtr(obj, ptr, ty, 0); } else { void *vptr = 0; /* here we get the method pointer for callbacks */ const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; if (desc) desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; if (!desc) return SWIG_ERROR; if (ty) { swig_cast_info *tc = SWIG_TypeCheck(desc,ty); if (tc) { int newmemory = 0; *ptr = SWIG_TypeCast(tc,vptr,&newmemory); assert(!newmemory); /* newmemory handling not yet implemented */ } else { return SWIG_ERROR; } } else { *ptr = vptr; } return SWIG_OK; } } /* Convert a packed value value */ SWIGRUNTIME int SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz); if (!to) return SWIG_ERROR; if (ty) { if (to != ty) { /* check type cast? */ swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); if (!tc) return SWIG_ERROR; } } return SWIG_OK; } /* ----------------------------------------------------------------------------- * Create a new pointer object * ----------------------------------------------------------------------------- */ /* Create a new instance object, without calling __init__, and set the 'this' attribute. */ SWIGRUNTIME PyObject* SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) { #if (PY_VERSION_HEX >= 0x02020000) PyObject *inst = 0; PyObject *newraw = data->newraw; if (newraw) { inst = PyObject_Call(newraw, data->newargs, NULL); if (inst) { #if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) PyObject **dictptr = _PyObject_GetDictPtr(inst); if (dictptr != NULL) { PyObject *dict = *dictptr; if (dict == NULL) { dict = PyDict_New(); *dictptr = dict; PyDict_SetItem(dict, SWIG_This(), swig_this); } } #else PyObject *key = SWIG_This(); PyObject_SetAttr(inst, key, swig_this); #endif } } else { #if PY_VERSION_HEX >= 0x03000000 inst = ((PyTypeObject*) data->newargs)->tp_new((PyTypeObject*) data->newargs, Py_None, Py_None); if (inst) { PyObject_SetAttr(inst, SWIG_This(), swig_this); Py_TYPE(inst)->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; } #else PyObject *dict = PyDict_New(); if (dict) { PyDict_SetItem(dict, SWIG_This(), swig_this); inst = PyInstance_NewRaw(data->newargs, dict); Py_DECREF(dict); } #endif } return inst; #else #if (PY_VERSION_HEX >= 0x02010000) PyObject *inst = 0; PyObject *dict = PyDict_New(); if (dict) { PyDict_SetItem(dict, SWIG_This(), swig_this); inst = PyInstance_NewRaw(data->newargs, dict); Py_DECREF(dict); } return (PyObject *) inst; #else PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type); if (inst == NULL) { return NULL; } inst->in_class = (PyClassObject *)data->newargs; Py_INCREF(inst->in_class); inst->in_dict = PyDict_New(); if (inst->in_dict == NULL) { Py_DECREF(inst); return NULL; } #ifdef Py_TPFLAGS_HAVE_WEAKREFS inst->in_weakreflist = NULL; #endif #ifdef Py_TPFLAGS_GC PyObject_GC_Init(inst); #endif PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this); return (PyObject *) inst; #endif #endif } SWIGRUNTIME void SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) { PyObject *dict; #if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS) PyObject **dictptr = _PyObject_GetDictPtr(inst); if (dictptr != NULL) { dict = *dictptr; if (dict == NULL) { dict = PyDict_New(); *dictptr = dict; } PyDict_SetItem(dict, SWIG_This(), swig_this); return; } #endif dict = PyObject_GetAttrString(inst, (char*)"__dict__"); PyDict_SetItem(dict, SWIG_This(), swig_this); Py_DECREF(dict); } SWIGINTERN PyObject * SWIG_Python_InitShadowInstance(PyObject *args) { PyObject *obj[2]; if (!SWIG_Python_UnpackTuple(args, "swiginit", 2, 2, obj)) { return NULL; } else { SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); if (sthis) { SwigPyObject_append((PyObject*) sthis, obj[1]); } else { SWIG_Python_SetSwigThis(obj[0], obj[1]); } return SWIG_Py_Void(); } } /* Create a new pointer object */ SWIGRUNTIME PyObject * SWIG_Python_NewPointerObj(PyObject *self, void *ptr, swig_type_info *type, int flags) { SwigPyClientData *clientdata; PyObject * robj; int own; if (!ptr) return SWIG_Py_Void(); clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0; own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; if (clientdata && clientdata->pytype) { SwigPyObject *newobj; if (flags & SWIG_BUILTIN_TP_INIT) { newobj = (SwigPyObject*) self; if (newobj->ptr) { PyObject *next_self = clientdata->pytype->tp_alloc(clientdata->pytype, 0); while (newobj->next) newobj = (SwigPyObject *) newobj->next; newobj->next = next_self; newobj = (SwigPyObject *)next_self; } } else { newobj = PyObject_New(SwigPyObject, clientdata->pytype); } if (newobj) { newobj->ptr = ptr; newobj->ty = type; newobj->own = own; newobj->next = 0; #ifdef SWIGPYTHON_BUILTIN newobj->dict = 0; #endif return (PyObject*) newobj; } return SWIG_Py_Void(); } assert(!(flags & SWIG_BUILTIN_TP_INIT)); robj = SwigPyObject_New(ptr, type, own); if (robj && clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); Py_DECREF(robj); robj = inst; } return robj; } /* Create a new packed object */ SWIGRUNTIMEINLINE PyObject * SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); } /* -----------------------------------------------------------------------------* * Get type list * -----------------------------------------------------------------------------*/ #ifdef SWIG_LINK_RUNTIME void *SWIG_ReturnGlobalTypeList(void *); #endif SWIGRUNTIME swig_module_info * SWIG_Python_GetModule(void *SWIGUNUSEDPARM(clientdata)) { static void *type_pointer = (void *)0; /* first check if module already created */ if (!type_pointer) { #ifdef SWIG_LINK_RUNTIME type_pointer = SWIG_ReturnGlobalTypeList((void *)0); #else # ifdef SWIGPY_USE_CAPSULE type_pointer = PyCapsule_Import(SWIGPY_CAPSULE_NAME, 0); # else type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME); # endif if (PyErr_Occurred()) { PyErr_Clear(); type_pointer = (void *)0; } #endif } return (swig_module_info *) type_pointer; } #if PY_MAJOR_VERSION < 2 /* PyModule_AddObject function was introduced in Python 2.0. The following function is copied out of Python/modsupport.c in python version 2.3.4 */ SWIGINTERN int PyModule_AddObject(PyObject *m, char *name, PyObject *o) { PyObject *dict; if (!PyModule_Check(m)) { PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs module as first arg"); return SWIG_ERROR; } if (!o) { PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs non-NULL value"); return SWIG_ERROR; } dict = PyModule_GetDict(m); if (dict == NULL) { /* Internal error -- modules must have a dict! */ PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", PyModule_GetName(m)); return SWIG_ERROR; } if (PyDict_SetItemString(dict, name, o)) return SWIG_ERROR; Py_DECREF(o); return SWIG_OK; } #endif SWIGRUNTIME void #ifdef SWIGPY_USE_CAPSULE SWIG_Python_DestroyModule(PyObject *obj) #else SWIG_Python_DestroyModule(void *vptr) #endif { #ifdef SWIGPY_USE_CAPSULE swig_module_info *swig_module = (swig_module_info *) PyCapsule_GetPointer(obj, SWIGPY_CAPSULE_NAME); #else swig_module_info *swig_module = (swig_module_info *) vptr; #endif swig_type_info **types = swig_module->types; size_t i; for (i =0; i < swig_module->size; ++i) { swig_type_info *ty = types[i]; if (ty->owndata) { SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; if (data) SwigPyClientData_Del(data); } } Py_DECREF(SWIG_This()); swig_this = NULL; } SWIGRUNTIME void SWIG_Python_SetModule(swig_module_info *swig_module) { #if PY_VERSION_HEX >= 0x03000000 /* Add a dummy module object into sys.modules */ PyObject *module = PyImport_AddModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION); #else static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} }; /* Sentinel */ PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table); #endif #ifdef SWIGPY_USE_CAPSULE PyObject *pointer = PyCapsule_New((void *) swig_module, SWIGPY_CAPSULE_NAME, SWIG_Python_DestroyModule); if (pointer && module) { PyModule_AddObject(module, (char*)"type_pointer_capsule" SWIG_TYPE_TABLE_NAME, pointer); } else { Py_XDECREF(pointer); } #else PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule); if (pointer && module) { PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer); } else { Py_XDECREF(pointer); } #endif } /* The python cached type query */ SWIGRUNTIME PyObject * SWIG_Python_TypeCache(void) { static PyObject *SWIG_STATIC_POINTER(cache) = PyDict_New(); return cache; } SWIGRUNTIME swig_type_info * SWIG_Python_TypeQuery(const char *type) { PyObject *cache = SWIG_Python_TypeCache(); PyObject *key = SWIG_Python_str_FromChar(type); PyObject *obj = PyDict_GetItem(cache, key); swig_type_info *descriptor; if (obj) { #ifdef SWIGPY_USE_CAPSULE descriptor = (swig_type_info *) PyCapsule_GetPointer(obj, NULL); #else descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj); #endif } else { swig_module_info *swig_module = SWIG_GetModule(0); descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); if (descriptor) { #ifdef SWIGPY_USE_CAPSULE obj = PyCapsule_New((void*) descriptor, NULL, NULL); #else obj = PyCObject_FromVoidPtr(descriptor, NULL); #endif PyDict_SetItem(cache, key, obj); Py_DECREF(obj); } } Py_DECREF(key); return descriptor; } /* For backward compatibility only */ #define SWIG_POINTER_EXCEPTION 0 #define SWIG_arg_fail(arg) SWIG_Python_ArgFail(arg) #define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) SWIGRUNTIME int SWIG_Python_AddErrMesg(const char* mesg, int infront) { if (PyErr_Occurred()) { PyObject *type = 0; PyObject *value = 0; PyObject *traceback = 0; PyErr_Fetch(&type, &value, &traceback); if (value) { char *tmp; PyObject *old_str = PyObject_Str(value); Py_XINCREF(type); PyErr_Clear(); if (infront) { PyErr_Format(type, "%s %s", mesg, tmp = SWIG_Python_str_AsChar(old_str)); } else { PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); } SWIG_Python_str_DelForPy3(tmp); Py_DECREF(old_str); } return 1; } else { return 0; } } SWIGRUNTIME int SWIG_Python_ArgFail(int argnum) { if (PyErr_Occurred()) { /* add information about failing argument */ char mesg[256]; PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); return SWIG_Python_AddErrMesg(mesg, 1); } else { return 0; } } SWIGRUNTIMEINLINE const char * SwigPyObject_GetDesc(PyObject *self) { SwigPyObject *v = (SwigPyObject *)self; swig_type_info *ty = v ? v->ty : 0; return ty ? ty->str : ""; } SWIGRUNTIME void SWIG_Python_TypeError(const char *type, PyObject *obj) { if (type) { #if defined(SWIG_COBJECT_TYPES) if (obj && SwigPyObject_Check(obj)) { const char *otype = (const char *) SwigPyObject_GetDesc(obj); if (otype) { PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received", type, otype); return; } } else #endif { const char *otype = (obj ? obj->ob_type->tp_name : 0); if (otype) { PyObject *str = PyObject_Str(obj); const char *cstr = str ? SWIG_Python_str_AsChar(str) : 0; if (cstr) { PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", type, otype, cstr); SWIG_Python_str_DelForPy3(cstr); } else { PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", type, otype); } Py_XDECREF(str); return; } } PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); } else { PyErr_Format(PyExc_TypeError, "unexpected type is received"); } } /* Convert a pointer value, signal an exception on a type mismatch */ SWIGRUNTIME void * SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int SWIGUNUSEDPARM(argnum), int flags) { void *result; if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { PyErr_Clear(); #if SWIG_POINTER_EXCEPTION if (flags) { SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj); SWIG_Python_ArgFail(argnum); } #endif } return result; } #ifdef SWIGPYTHON_BUILTIN SWIGRUNTIME int SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) { PyTypeObject *tp = obj->ob_type; PyObject *descr; PyObject *encoded_name; descrsetfunc f; int res = -1; # ifdef Py_USING_UNICODE if (PyString_Check(name)) { name = PyUnicode_Decode(PyString_AsString(name), PyString_Size(name), NULL, NULL); if (!name) return -1; } else if (!PyUnicode_Check(name)) # else if (!PyString_Check(name)) # endif { PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); return -1; } else { Py_INCREF(name); } if (!tp->tp_dict) { if (PyType_Ready(tp) < 0) goto done; } descr = _PyType_Lookup(tp, name); f = NULL; if (descr != NULL) f = descr->ob_type->tp_descr_set; if (!f) { if (PyString_Check(name)) { encoded_name = name; Py_INCREF(name); } else { encoded_name = PyUnicode_AsUTF8String(name); } PyErr_Format(PyExc_AttributeError, "'%.100s' object has no attribute '%.200s'", tp->tp_name, PyString_AsString(encoded_name)); Py_DECREF(encoded_name); } else { res = f(descr, obj, value); } done: Py_DECREF(name); return res; } #endif #ifdef __cplusplus } #endif #define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) #define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else /* -------- TYPES TABLE (BEGIN) -------- */ #define SWIGTYPE_p_char swig_types[0] #define SWIGTYPE_p_int swig_types[1] #define SWIGTYPE_p_long_long swig_types[2] #define SWIGTYPE_p_short swig_types[3] #define SWIGTYPE_p_signed_char swig_types[4] #define SWIGTYPE_p_unsigned_char swig_types[5] #define SWIGTYPE_p_unsigned_int swig_types[6] #define SWIGTYPE_p_unsigned_long_long swig_types[7] #define SWIGTYPE_p_unsigned_short swig_types[8] static swig_type_info *swig_types[10]; static swig_module_info swig_module = {swig_types, 9, 0, 0, 0, 0}; #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) /* -------- TYPES TABLE (END) -------- */ #if (PY_VERSION_HEX <= 0x02000000) # if !defined(SWIG_PYTHON_CLASSIC) # error "This python version requires swig to be run with the '-classic' option" # endif #endif /*----------------------------------------------- @(target):= _blinkt.so ------------------------------------------------*/ #if PY_VERSION_HEX >= 0x03000000 # define SWIG_init PyInit__blinkt #else # define SWIG_init init_blinkt #endif #define SWIG_name "_blinkt" #define SWIGVERSION 0x030002 #define SWIG_VERSION SWIGVERSION #define SWIG_as_voidptr(a) (void *)((const void *)(a)) #define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) #include // Use the C99 official header #include "lib/blinkt.h" #include #if !defined(SWIG_NO_LLONG_MAX) # if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__) # define LLONG_MAX __LONG_LONG_MAX__ # define LLONG_MIN (-LLONG_MAX - 1LL) # define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL) # endif #endif SWIGINTERN int SWIG_AsVal_double (PyObject *obj, double *val) { int res = SWIG_TypeError; if (PyFloat_Check(obj)) { if (val) *val = PyFloat_AsDouble(obj); return SWIG_OK; } else if (PyInt_Check(obj)) { if (val) *val = PyInt_AsLong(obj); return SWIG_OK; } else if (PyLong_Check(obj)) { double v = PyLong_AsDouble(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } #ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; double d = PyFloat_AsDouble(obj); if (!PyErr_Occurred()) { if (val) *val = d; return SWIG_AddCast(SWIG_OK); } else { PyErr_Clear(); } if (!dispatch) { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_AddCast(SWIG_AddCast(SWIG_OK)); } else { PyErr_Clear(); } } } #endif return res; } #include #include SWIGINTERNINLINE int SWIG_CanCastAsInteger(double *d, double min, double max) { double x = *d; if ((min <= x && x <= max)) { double fx = floor(x); double cx = ceil(x); double rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ if ((errno == EDOM) || (errno == ERANGE)) { errno = 0; } else { double summ, reps, diff; if (rd < x) { diff = x - rd; } else if (rd > x) { diff = rd - x; } else { return 1; } summ = rd + x; reps = diff/summ; if (reps < 8*DBL_EPSILON) { *d = rd; return 1; } } } return 0; } SWIGINTERN int SWIG_AsVal_unsigned_SS_long (PyObject *obj, unsigned long *val) { #if PY_VERSION_HEX < 0x03000000 if (PyInt_Check(obj)) { long v = PyInt_AsLong(obj); if (v >= 0) { if (val) *val = v; return SWIG_OK; } else { return SWIG_OverflowError; } } else #endif if (PyLong_Check(obj)) { unsigned long v = PyLong_AsUnsignedLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); #if PY_VERSION_HEX >= 0x03000000 { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (v < 0) { return SWIG_OverflowError; } } else { PyErr_Clear(); } } #endif } } #ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; unsigned long v = PyLong_AsUnsignedLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_AddCast(SWIG_OK); } else { PyErr_Clear(); } if (!dispatch) { double d; int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, 0, ULONG_MAX)) { if (val) *val = (unsigned long)(d); return res; } } } #endif return SWIG_TypeError; } SWIGINTERN int SWIG_AsVal_unsigned_SS_char (PyObject * obj, unsigned char *val) { unsigned long v; int res = SWIG_AsVal_unsigned_SS_long (obj, &v); if (SWIG_IsOK(res)) { if ((v > UCHAR_MAX)) { return SWIG_OverflowError; } else { if (val) *val = (unsigned char)(v); } } return res; } SWIGINTERN int SWIG_AsVal_unsigned_SS_int (PyObject * obj, unsigned int *val) { unsigned long v; int res = SWIG_AsVal_unsigned_SS_long (obj, &v); if (SWIG_IsOK(res)) { if ((v > UINT_MAX)) { return SWIG_OverflowError; } else { if (val) *val = (unsigned int)(v); } } return res; } SWIGINTERNINLINE PyObject* SWIG_From_unsigned_SS_int (unsigned int value) { return PyInt_FromSize_t((size_t) value); } SWIGINTERNINLINE PyObject* SWIG_From_int (int value) { return PyInt_FromLong((long) value); } #ifdef __cplusplus extern "C" { #endif SWIGINTERN PyObject *_wrap_clear(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; if (!PyArg_ParseTuple(args,(char *)":clear")) SWIG_fail; clear(); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_set_pixel_uint32(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; uint8_t arg1 ; uint32_t arg2 ; unsigned char val1 ; int ecode1 = 0 ; unsigned int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:set_pixel_uint32",&obj0,&obj1)) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_char(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "set_pixel_uint32" "', argument " "1"" of type '" "uint8_t""'"); } arg1 = (uint8_t)(val1); ecode2 = SWIG_AsVal_unsigned_SS_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "set_pixel_uint32" "', argument " "2"" of type '" "uint32_t""'"); } arg2 = (uint32_t)(val2); set_pixel_uint32(arg1,arg2); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_set_pixel(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; uint8_t arg1 ; uint8_t arg2 ; uint8_t arg3 ; uint8_t arg4 ; unsigned char val1 ; int ecode1 = 0 ; unsigned char val2 ; int ecode2 = 0 ; unsigned char val3 ; int ecode3 = 0 ; unsigned char val4 ; int ecode4 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PyObject * obj3 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OOOO:set_pixel",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_char(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "set_pixel" "', argument " "1"" of type '" "uint8_t""'"); } arg1 = (uint8_t)(val1); ecode2 = SWIG_AsVal_unsigned_SS_char(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "set_pixel" "', argument " "2"" of type '" "uint8_t""'"); } arg2 = (uint8_t)(val2); ecode3 = SWIG_AsVal_unsigned_SS_char(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "set_pixel" "', argument " "3"" of type '" "uint8_t""'"); } arg3 = (uint8_t)(val3); ecode4 = SWIG_AsVal_unsigned_SS_char(obj3, &val4); if (!SWIG_IsOK(ecode4)) { SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "set_pixel" "', argument " "4"" of type '" "uint8_t""'"); } arg4 = (uint8_t)(val4); set_pixel(arg1,arg2,arg3,arg4); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_set_pixel_brightness(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; uint8_t arg1 ; uint8_t arg2 ; unsigned char val1 ; int ecode1 = 0 ; unsigned char val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:set_pixel_brightness",&obj0,&obj1)) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_char(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "set_pixel_brightness" "', argument " "1"" of type '" "uint8_t""'"); } arg1 = (uint8_t)(val1); ecode2 = SWIG_AsVal_unsigned_SS_char(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "set_pixel_brightness" "', argument " "2"" of type '" "uint8_t""'"); } arg2 = (uint8_t)(val2); set_pixel_brightness(arg1,arg2); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_rgbb(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; uint8_t arg1 ; uint8_t arg2 ; uint8_t arg3 ; uint8_t arg4 ; unsigned char val1 ; int ecode1 = 0 ; unsigned char val2 ; int ecode2 = 0 ; unsigned char val3 ; int ecode3 = 0 ; unsigned char val4 ; int ecode4 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PyObject * obj3 = 0 ; uint32_t result; if (!PyArg_ParseTuple(args,(char *)"OOOO:rgbb",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_char(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "rgbb" "', argument " "1"" of type '" "uint8_t""'"); } arg1 = (uint8_t)(val1); ecode2 = SWIG_AsVal_unsigned_SS_char(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "rgbb" "', argument " "2"" of type '" "uint8_t""'"); } arg2 = (uint8_t)(val2); ecode3 = SWIG_AsVal_unsigned_SS_char(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "rgbb" "', argument " "3"" of type '" "uint8_t""'"); } arg3 = (uint8_t)(val3); ecode4 = SWIG_AsVal_unsigned_SS_char(obj3, &val4); if (!SWIG_IsOK(ecode4)) { SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "rgbb" "', argument " "4"" of type '" "uint8_t""'"); } arg4 = (uint8_t)(val4); result = (uint32_t)rgbb(arg1,arg2,arg3,arg4); resultobj = SWIG_From_unsigned_SS_int((unsigned int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_rgb(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; uint8_t arg1 ; uint8_t arg2 ; uint8_t arg3 ; unsigned char val1 ; int ecode1 = 0 ; unsigned char val2 ; int ecode2 = 0 ; unsigned char val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; uint32_t result; if (!PyArg_ParseTuple(args,(char *)"OOO:rgb",&obj0,&obj1,&obj2)) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_char(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "rgb" "', argument " "1"" of type '" "uint8_t""'"); } arg1 = (uint8_t)(val1); ecode2 = SWIG_AsVal_unsigned_SS_char(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "rgb" "', argument " "2"" of type '" "uint8_t""'"); } arg2 = (uint8_t)(val2); ecode3 = SWIG_AsVal_unsigned_SS_char(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "rgb" "', argument " "3"" of type '" "uint8_t""'"); } arg3 = (uint8_t)(val3); result = (uint32_t)rgb(arg1,arg2,arg3); resultobj = SWIG_From_unsigned_SS_int((unsigned int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_stop(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; if (!PyArg_ParseTuple(args,(char *)":stop")) SWIG_fail; stop(); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_start(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; int result; if (!PyArg_ParseTuple(args,(char *)":start")) SWIG_fail; result = (int)start(); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_show(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; if (!PyArg_ParseTuple(args,(char *)":show")) SWIG_fail; show(); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } static PyMethodDef SwigMethods[] = { { (char *)"SWIG_PyInstanceMethod_New", (PyCFunction)SWIG_PyInstanceMethod_New, METH_O, NULL}, { (char *)"clear", _wrap_clear, METH_VARARGS, NULL}, { (char *)"set_pixel_uint32", _wrap_set_pixel_uint32, METH_VARARGS, NULL}, { (char *)"set_pixel", _wrap_set_pixel, METH_VARARGS, NULL}, { (char *)"set_pixel_brightness", _wrap_set_pixel_brightness, METH_VARARGS, NULL}, { (char *)"rgbb", _wrap_rgbb, METH_VARARGS, NULL}, { (char *)"rgb", _wrap_rgb, METH_VARARGS, NULL}, { (char *)"stop", _wrap_stop, METH_VARARGS, NULL}, { (char *)"start", _wrap_start, METH_VARARGS, NULL}, { (char *)"show", _wrap_show, METH_VARARGS, NULL}, { NULL, NULL, 0, NULL } }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_int = {"_p_int", "intptr_t *|int *|int_least32_t *|int_fast32_t *|int32_t *|int_fast16_t *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_long_long = {"_p_long_long", "int_least64_t *|int_fast64_t *|int64_t *|long long *|intmax_t *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_short = {"_p_short", "short *|int_least16_t *|int16_t *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_signed_char = {"_p_signed_char", "signed char *|int_least8_t *|int_fast8_t *|int8_t *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_unsigned_char = {"_p_unsigned_char", "unsigned char *|uint_least8_t *|uint_fast8_t *|uint8_t *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_unsigned_int = {"_p_unsigned_int", "uintptr_t *|uint_least32_t *|uint_fast32_t *|uint32_t *|unsigned int *|uint_fast16_t *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_unsigned_long_long = {"_p_unsigned_long_long", "uint_least64_t *|uint_fast64_t *|uint64_t *|unsigned long long *|uintmax_t *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_unsigned_short = {"_p_unsigned_short", "unsigned short *|uint_least16_t *|uint16_t *", 0, 0, (void*)0, 0}; static swig_type_info *swig_type_initial[] = { &_swigt__p_char, &_swigt__p_int, &_swigt__p_long_long, &_swigt__p_short, &_swigt__p_signed_char, &_swigt__p_unsigned_char, &_swigt__p_unsigned_int, &_swigt__p_unsigned_long_long, &_swigt__p_unsigned_short, }; static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_int[] = { {&_swigt__p_int, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_long_long[] = { {&_swigt__p_long_long, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_short[] = { {&_swigt__p_short, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_signed_char[] = { {&_swigt__p_signed_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_unsigned_char[] = { {&_swigt__p_unsigned_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_unsigned_int[] = { {&_swigt__p_unsigned_int, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_unsigned_long_long[] = { {&_swigt__p_unsigned_long_long, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_unsigned_short[] = { {&_swigt__p_unsigned_short, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { _swigc__p_char, _swigc__p_int, _swigc__p_long_long, _swigc__p_short, _swigc__p_signed_char, _swigc__p_unsigned_char, _swigc__p_unsigned_int, _swigc__p_unsigned_long_long, _swigc__p_unsigned_short, }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ static swig_const_info swig_const_table[] = { {0, 0, 0, 0.0, 0, 0}}; #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * Type initialization: * This problem is tough by the requirement that no dynamic * memory is used. Also, since swig_type_info structures store pointers to * swig_cast_info structures and swig_cast_info structures store pointers back * to swig_type_info structures, we need some lookup code at initialization. * The idea is that swig generates all the structures that are needed. * The runtime then collects these partially filled structures. * The SWIG_InitializeModule function takes these initial arrays out of * swig_module, and does all the lookup, filling in the swig_module.types * array with the correct data and linking the correct swig_cast_info * structures together. * * The generated swig_type_info structures are assigned statically to an initial * array. We just loop through that array, and handle each type individually. * First we lookup if this type has been already loaded, and if so, use the * loaded structure instead of the generated one. Then we have to fill in the * cast linked list. The cast data is initially stored in something like a * two-dimensional array. Each row corresponds to a type (there are the same * number of rows as there are in the swig_type_initial array). Each entry in * a column is one of the swig_cast_info structures for that type. * The cast_initial array is actually an array of arrays, because each row has * a variable number of columns. So to actually build the cast linked list, * we find the array of casts associated with the type, and loop through it * adding the casts to the list. The one last trick we need to do is making * sure the type pointer in the swig_cast_info struct is correct. * * First off, we lookup the cast->type name to see if it is already loaded. * There are three cases to handle: * 1) If the cast->type has already been loaded AND the type we are adding * casting info to has not been loaded (it is in this module), THEN we * replace the cast->type pointer with the type pointer that has already * been loaded. * 2) If BOTH types (the one we are adding casting info to, and the * cast->type) are loaded, THEN the cast info has already been loaded by * the previous module so we just ignore it. * 3) Finally, if cast->type has not already been loaded, then we add that * swig_cast_info to the linked list (because the cast->type) pointer will * be correct. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* c-mode */ #endif #endif #if 0 #define SWIGRUNTIME_DEBUG #endif SWIGRUNTIME void SWIG_InitializeModule(void *clientdata) { size_t i; swig_module_info *module_head, *iter; int found, init; /* check to see if the circular list has been setup, if not, set it up */ if (swig_module.next==0) { /* Initialize the swig_module */ swig_module.type_initial = swig_type_initial; swig_module.cast_initial = swig_cast_initial; swig_module.next = &swig_module; init = 1; } else { init = 0; } /* Try and load any already created modules */ module_head = SWIG_GetModule(clientdata); if (!module_head) { /* This is the first module loaded for this interpreter */ /* so set the swig module into the interpreter */ SWIG_SetModule(clientdata, &swig_module); module_head = &swig_module; } else { /* the interpreter has loaded a SWIG module, but has it loaded this one? */ found=0; iter=module_head; do { if (iter==&swig_module) { found=1; break; } iter=iter->next; } while (iter!= module_head); /* if the is found in the list, then all is done and we may leave */ if (found) return; /* otherwise we must add out module into the list */ swig_module.next = module_head->next; module_head->next = &swig_module; } /* When multiple interpreters are used, a module could have already been initialized in a different interpreter, but not yet have a pointer in this interpreter. In this case, we do not want to continue adding types... everything should be set up already */ if (init == 0) return; /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: size %d\n", swig_module.size); #endif for (i = 0; i < swig_module.size; ++i) { swig_type_info *type = 0; swig_type_info *ret; swig_cast_info *cast; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); #endif /* if there is another module already loaded */ if (swig_module.next != &swig_module) { type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); } if (type) { /* Overwrite clientdata field */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found type %s\n", type->name); #endif if (swig_module.type_initial[i]->clientdata) { type->clientdata = swig_module.type_initial[i]->clientdata; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); #endif } } else { type = swig_module.type_initial[i]; } /* Insert casting types */ cast = swig_module.cast_initial[i]; while (cast->type) { /* Don't need to add information already in the list */ ret = 0; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif if (swig_module.next != &swig_module) { ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); #ifdef SWIGRUNTIME_DEBUG if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); #endif } if (ret) { if (type == swig_module.type_initial[i]) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: skip old type %s\n", ret->name); #endif cast->type = ret; ret = 0; } else { /* Check for casting already in the list */ swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); #ifdef SWIGRUNTIME_DEBUG if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); #endif if (!ocast) ret = 0; } } if (!ret) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); #endif if (type->cast) { type->cast->prev = cast; cast->next = type->cast; } type->cast = cast; } cast++; } /* Set entry in modules->types array equal to the type */ swig_module.types[i] = type; } swig_module.types[i] = 0; #ifdef SWIGRUNTIME_DEBUG printf("**** SWIG_InitializeModule: Cast List ******\n"); for (i = 0; i < swig_module.size; ++i) { int j = 0; swig_cast_info *cast = swig_module.cast_initial[i]; printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); while (cast->type) { printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); cast++; ++j; } printf("---- Total casts: %d\n",j); } printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } /* This function will propagate the clientdata field of type to * any new swig_type_info structures that have been added into the list * of equivalent types. It is like calling * SWIG_TypeClientData(type, clientdata) a second time. */ SWIGRUNTIME void SWIG_PropagateClientData(void) { size_t i; swig_cast_info *equiv; static int init_run = 0; if (init_run) return; init_run = 1; for (i = 0; i < swig_module.size; i++) { if (swig_module.types[i]->clientdata) { equiv = swig_module.types[i]->cast; while (equiv) { if (!equiv->converter) { if (equiv->type && !equiv->type->clientdata) SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); } equiv = equiv->next; } } } } #ifdef __cplusplus #if 0 { /* c-mode */ #endif } #endif #ifdef __cplusplus extern "C" { #endif /* Python-specific SWIG API */ #define SWIG_newvarlink() SWIG_Python_newvarlink() #define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) #define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) /* ----------------------------------------------------------------------------- * global variable support code. * ----------------------------------------------------------------------------- */ typedef struct swig_globalvar { char *name; /* Name of global variable */ PyObject *(*get_attr)(void); /* Return the current value */ int (*set_attr)(PyObject *); /* Set the value */ struct swig_globalvar *next; } swig_globalvar; typedef struct swig_varlinkobject { PyObject_HEAD swig_globalvar *vars; } swig_varlinkobject; SWIGINTERN PyObject * swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) { #if PY_VERSION_HEX >= 0x03000000 return PyUnicode_InternFromString(""); #else return PyString_FromString(""); #endif } SWIGINTERN PyObject * swig_varlink_str(swig_varlinkobject *v) { #if PY_VERSION_HEX >= 0x03000000 PyObject *str = PyUnicode_InternFromString("("); PyObject *tail; PyObject *joined; swig_globalvar *var; for (var = v->vars; var; var=var->next) { tail = PyUnicode_FromString(var->name); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; if (var->next) { tail = PyUnicode_InternFromString(", "); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; } } tail = PyUnicode_InternFromString(")"); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; #else PyObject *str = PyString_FromString("("); swig_globalvar *var; for (var = v->vars; var; var=var->next) { PyString_ConcatAndDel(&str,PyString_FromString(var->name)); if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); } PyString_ConcatAndDel(&str,PyString_FromString(")")); #endif return str; } SWIGINTERN int swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { char *tmp; PyObject *str = swig_varlink_str(v); fprintf(fp,"Swig global variables "); fprintf(fp,"%s\n", tmp = SWIG_Python_str_AsChar(str)); SWIG_Python_str_DelForPy3(tmp); Py_DECREF(str); return 0; } SWIGINTERN void swig_varlink_dealloc(swig_varlinkobject *v) { swig_globalvar *var = v->vars; while (var) { swig_globalvar *n = var->next; free(var->name); free(var); var = n; } } SWIGINTERN PyObject * swig_varlink_getattr(swig_varlinkobject *v, char *n) { PyObject *res = NULL; swig_globalvar *var = v->vars; while (var) { if (strcmp(var->name,n) == 0) { res = (*var->get_attr)(); break; } var = var->next; } if (res == NULL && !PyErr_Occurred()) { PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); } return res; } SWIGINTERN int swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) { int res = 1; swig_globalvar *var = v->vars; while (var) { if (strcmp(var->name,n) == 0) { res = (*var->set_attr)(p); break; } var = var->next; } if (res == 1 && !PyErr_Occurred()) { PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); } return res; } SWIGINTERN PyTypeObject* swig_varlink_type(void) { static char varlink__doc__[] = "Swig var link object"; static PyTypeObject varlink_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX >= 0x03000000 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif (char *)"swigvarlink", /* tp_name */ sizeof(swig_varlinkobject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor) swig_varlink_dealloc, /* tp_dealloc */ (printfunc) swig_varlink_print, /* tp_print */ (getattrfunc) swig_varlink_getattr, /* tp_getattr */ (setattrfunc) swig_varlink_setattr, /* tp_setattr */ 0, /* tp_compare */ (reprfunc) swig_varlink_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc) swig_varlink_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ varlink__doc__, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #if PY_VERSION_HEX >= 0x02060000 0, /* tp_version */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; varlink_type = tmp; type_init = 1; #if PY_VERSION_HEX < 0x02020000 varlink_type.ob_type = &PyType_Type; #else if (PyType_Ready(&varlink_type) < 0) return NULL; #endif } return &varlink_type; } /* Create a variable linking object for use later */ SWIGINTERN PyObject * SWIG_Python_newvarlink(void) { swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type()); if (result) { result->vars = 0; } return ((PyObject*) result); } SWIGINTERN void SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { swig_varlinkobject *v = (swig_varlinkobject *) p; swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); if (gv) { size_t size = strlen(name)+1; gv->name = (char *)malloc(size); if (gv->name) { strncpy(gv->name,name,size); gv->get_attr = get_attr; gv->set_attr = set_attr; gv->next = v->vars; } } v->vars = gv; } SWIGINTERN PyObject * SWIG_globals(void) { static PyObject *_SWIG_globals = 0; if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink(); return _SWIG_globals; } /* ----------------------------------------------------------------------------- * constants/methods manipulation * ----------------------------------------------------------------------------- */ /* Install Constants */ SWIGINTERN void SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { PyObject *obj = 0; size_t i; for (i = 0; constants[i].type; ++i) { switch(constants[i].type) { case SWIG_PY_POINTER: obj = SWIG_InternalNewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); break; case SWIG_PY_BINARY: obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); break; default: obj = 0; break; } if (obj) { PyDict_SetItemString(d, constants[i].name, obj); Py_DECREF(obj); } } } /* -----------------------------------------------------------------------------*/ /* Fix SwigMethods to carry the callback ptrs when needed */ /* -----------------------------------------------------------------------------*/ SWIGINTERN void SWIG_Python_FixMethods(PyMethodDef *methods, swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) { size_t i; for (i = 0; methods[i].ml_name; ++i) { const char *c = methods[i].ml_doc; if (c && (c = strstr(c, "swig_ptr: "))) { int j; swig_const_info *ci = 0; const char *name = c + 10; for (j = 0; const_table[j].type; ++j) { if (strncmp(const_table[j].name, name, strlen(const_table[j].name)) == 0) { ci = &(const_table[j]); break; } } if (ci) { void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; if (ptr) { size_t shift = (ci->ptype) - types; swig_type_info *ty = types_initial[shift]; size_t ldoc = (c - methods[i].ml_doc); size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; char *ndoc = (char*)malloc(ldoc + lptr + 10); if (ndoc) { char *buff = ndoc; strncpy(buff, methods[i].ml_doc, ldoc); buff += ldoc; strncpy(buff, "swig_ptr: ", 10); buff += 10; SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); methods[i].ml_doc = ndoc; } } } } } } #ifdef __cplusplus } #endif /* -----------------------------------------------------------------------------* * Partial Init method * -----------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" #endif SWIGEXPORT #if PY_VERSION_HEX >= 0x03000000 PyObject* #else void #endif SWIG_init(void) { PyObject *m, *d, *md; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef SWIG_module = { # if PY_VERSION_HEX >= 0x03020000 PyModuleDef_HEAD_INIT, # else { PyObject_HEAD_INIT(NULL) NULL, /* m_init */ 0, /* m_index */ NULL, /* m_copy */ }, # endif (char *) SWIG_name, NULL, -1, SwigMethods, NULL, NULL, NULL, NULL }; #endif #if defined(SWIGPYTHON_BUILTIN) static SwigPyClientData SwigPyObject_clientdata = { 0, 0, 0, 0, 0, 0, 0 }; static PyGetSetDef this_getset_def = { (char *)"this", &SwigPyBuiltin_ThisClosure, NULL, NULL, NULL }; static SwigPyGetSet thisown_getset_closure = { (PyCFunction) SwigPyObject_own, (PyCFunction) SwigPyObject_own }; static PyGetSetDef thisown_getset_def = { (char *)"thisown", SwigPyBuiltin_GetterClosure, SwigPyBuiltin_SetterClosure, NULL, &thisown_getset_closure }; PyObject *metatype_args; PyTypeObject *builtin_pytype; int builtin_base_count; swig_type_info *builtin_basetype; PyObject *tuple; PyGetSetDescrObject *static_getset; PyTypeObject *metatype; SwigPyClientData *cd; PyObject *public_interface, *public_symbol; PyObject *this_descr; PyObject *thisown_descr; int i; (void)builtin_pytype; (void)builtin_base_count; (void)builtin_basetype; (void)tuple; (void)static_getset; /* metatype is used to implement static member variables. */ metatype_args = Py_BuildValue("(s(O){})", "SwigPyObjectType", &PyType_Type); assert(metatype_args); metatype = (PyTypeObject *) PyType_Type.tp_call((PyObject *) &PyType_Type, metatype_args, NULL); assert(metatype); Py_DECREF(metatype_args); metatype->tp_setattro = (setattrofunc) &SwigPyObjectType_setattro; assert(PyType_Ready(metatype) >= 0); #endif /* Fix SwigMethods to carry the callback ptrs when needed */ SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); #if PY_VERSION_HEX >= 0x03000000 m = PyModule_Create(&SWIG_module); #else m = Py_InitModule((char *) SWIG_name, SwigMethods); #endif md = d = PyModule_GetDict(m); (void)md; SWIG_InitializeModule(0); #ifdef SWIGPYTHON_BUILTIN SwigPyObject_stype = SWIG_MangledTypeQuery("_p_SwigPyObject"); assert(SwigPyObject_stype); cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; if (!cd) { SwigPyObject_stype->clientdata = &SwigPyObject_clientdata; SwigPyObject_clientdata.pytype = SwigPyObject_TypeOnce(); } else if (SwigPyObject_TypeOnce()->tp_basicsize != cd->pytype->tp_basicsize) { PyErr_SetString(PyExc_RuntimeError, "Import error: attempted to load two incompatible swig-generated modules."); # if PY_VERSION_HEX >= 0x03000000 return NULL; # else return; # endif } /* All objects have a 'this' attribute */ this_descr = PyDescr_NewGetSet(SwigPyObject_type(), &this_getset_def); (void)this_descr; /* All objects have a 'thisown' attribute */ thisown_descr = PyDescr_NewGetSet(SwigPyObject_type(), &thisown_getset_def); (void)thisown_descr; public_interface = PyList_New(0); public_symbol = 0; (void)public_symbol; PyDict_SetItemString(md, "__all__", public_interface); Py_DECREF(public_interface); for (i = 0; SwigMethods[i].ml_name != NULL; ++i) SwigPyBuiltin_AddPublicSymbol(public_interface, SwigMethods[i].ml_name); for (i = 0; swig_const_table[i].name != 0; ++i) SwigPyBuiltin_AddPublicSymbol(public_interface, swig_const_table[i].name); #endif SWIG_InstallConstants(d,swig_const_table); #if PY_VERSION_HEX >= 0x03000000 return m; #else return; #endif } ================================================ FILE: library_c/lib/blinkt.c ================================================ #include #include #include #include #include #include #include #include "blinkt.h" #define APA_SOF 0b11100000 #define DEFAULT_BRIGHTNESS 7 #define NUM_LEDS 8 #define MOSI 23 #define SCLK 24 #ifdef TEST volatile int running = 0; #endif int x; uint32_t leds[NUM_LEDS] = {}; #ifdef TEST void sigint_handler(int dummy){ running = 0; return; } #endif void clear(){ for(x = 0; x < NUM_LEDS; x++){ leds[x] = DEFAULT_BRIGHTNESS; } } void set_pixel(uint8_t led, uint8_t r, uint8_t g, uint8_t b){ if(led >= NUM_LEDS) return; leds[led] = rgbb(r,g,b,leds[led] & 0b11111); } void set_pixel_brightness(uint8_t led, uint8_t brightness){ if(led >= NUM_LEDS) return; leds[led] = (leds[led] & 0xFFFFFF00) | (brightness & 0b11111); } void set_pixel_uint32(uint8_t led, uint32_t color){ if(led >= NUM_LEDS) return; leds[led] = color; } uint32_t rgbb(uint8_t r, uint8_t g, uint8_t b, uint8_t brightness){ uint32_t result = 0; result = (brightness & 0b11111); result |= ((uint32_t)r << 24); result |= ((uint32_t)g << 16); result |= ((uint16_t)b << 8); return result; } uint32_t rgb(uint8_t r, uint8_t g, uint8_t b){ return rgbb(r, g, b, DEFAULT_BRIGHTNESS); } inline static void write_byte(uint8_t byte){ int n; for(n = 0; n < 8; n++){ bcm2835_gpio_write(MOSI, (byte & (1 << (7-n))) > 0); bcm2835_gpio_write(SCLK, HIGH); bcm2835_gpio_write(SCLK, LOW); } } void show(void){ write_byte(0); write_byte(0); write_byte(0); write_byte(0); for(x = 0; x < NUM_LEDS; x++){ write_byte(APA_SOF | (leds[x] & 0b11111)); write_byte((leds[x] >> 8 ) & 0xFF); write_byte((leds[x] >> 16) & 0xFF); write_byte((leds[x] >> 24) & 0xFF); } write_byte(0xff); //write_byte(0xff); //write_byte(0xff); //write_byte(0xff); } void stop(void){ bcm2835_spi_end(); bcm2835_close(); } int start(void){ if(!bcm2835_init()) return 1; #ifdef TEST printf("GPIO Initialized\n"); #endif bcm2835_gpio_fsel(MOSI, BCM2835_GPIO_FSEL_OUTP); bcm2835_gpio_write(MOSI, LOW); bcm2835_gpio_fsel(SCLK, BCM2835_GPIO_FSEL_OUTP); bcm2835_gpio_write(SCLK, LOW); clear(); return 0; } #ifdef TEST int main(){ int z; int y = 0; running = 1; signal(SIGINT, sigint_handler); if (start()){ printf("Unable to start apa102\n"); return 1; } printf("Running test cycle\n"); int col = 0; while(running){ for(z = 0; z < NUM_LEDS; z++){ switch(col){ case 0: set_pixel_uint32(z, rgb(y,0,0)); break; case 1: set_pixel_uint32(z, rgb(0,y,0)); break; case 2: set_pixel_uint32(z, rgb(0,0,y)); break; } } show(); usleep(1000); y+=1; if(y>254) col++; col%=3; y%=255; } clear(); usleep(1000); stop(); return 0; } #endif ================================================ FILE: library_c/lib/blinkt.h ================================================ void clear(void); void set_pixel_uint32(uint8_t led, uint32_t color); void set_pixel(uint8_t led, uint8_t r, uint8_t g, uint8_t b); void set_pixel_brightness(uint8_t led, uint8_t brightness); uint32_t rgbb(uint8_t r, uint8_t g, uint8_t b, uint8_t brightness); uint32_t rgb(uint8_t r, uint8_t g, uint8_t b); void stop(void); int start(void); void show(void); ================================================ FILE: library_c/setup.py ================================================ #!/usr/bin/env python from setuptools import setup, find_packages, Extension _blinkt = Extension( '_blinkt', include_dirs=['lib'], libraries=['bcm2835'], sources=['lib/blinkt.c','blinkt_wrap.c'] ) setup( name = 'blinkt_c', version = '0.0.1', author = "Philip Howard", author_email = "phil@pimoroni.com", url = "", description = "", long_description = "", ext_modules = [ _blinkt ], py_modules = ["blinkt"], install_requires = [], headers=['lib/blinkt.h'] ) ================================================ FILE: packaging/CHANGELOG ================================================ blinkt (0.1.2) STABLE; urgency=low * BugFix: Added sleep to data output, see: https://github.com/pimoroni/blinkt/issues/62 -- Phil Howard Wed, 23 May 2018 00:00:00 +0000 blinkt (0.1.1) STABLE; urgency=low * New: Added `get_pixel` to return colour and brightness of a single pixel -- Phil Howard Tue, 20 Feb 2018 00:00:00 +0000 blinkt (0.1.0) STABLE; urgency=low * Removed try/except from RPi.GPIO import, output was misleading at best * Reverted default behaviour of clear on exit -- Phil Howard Tue, 06 Sep 2016 00:00:00 +0000 blinkt (0.0.9) UNRELEASED; urgency=low * Added set_all method to set all pixels * Changed default behaviour of clear on exit to reduce module side-effects * Move GPIO initialisation to show() to reduce module side-effects -- Phil Howard Tue, 06 Sep 2016 00:00:00 +0000 blinkt (0.0.8) UNRELEASED; urgency=low * Tweaked some methods to show intent as implementation detail only * Added docstrings detailing public methods -- Phil Howard Tue, 06 Sep 2016 00:00:00 +0000 blinkt (0.0.7) UNRELEASED; urgency=low * Fixed bug with APA102 pixels that have a small, black die (vs the larger, paler one) -- Phil Howard Wed, 24 Aug 2016 00:00:00 +0000 blinkt (0.0.6) UNRELEASED; urgency=low * set_clear_on_exit now method -- Phil Howard Thu, 11 Aug 2016 00:00:00 +0000 blinkt (0.0.5) UNRELEASED; urgency=low * Range clamping and coercion to integers -- Phil Howard Wed, 22 Jun 2016 00:00:00 +0000 blinkt (0.0.4) UNRELEASED; urgency=low * Various bug fixes -- Phil Howard Tue, 21 Jun 2016 18:00:00 +0000 blinkt (0.0.3) UNRELEASED; urgency=low * Switch to Python -- Phil Howard Tue, 21 Jun 2016 12:00:00 +0000 blinkt (0.0.2) UNRELEASED; urgency=low * Bug fixes for C Library -- Phil Howard Tue, 21 Jun 2016 06:00:00 +0000 blinkt (0.0.1) UNRELEASED; urgency=low * Original C Library -- Phil Howard Tue, 21 Jun 2016 00:00:00 +0000 ================================================ FILE: packaging/debian/README ================================================ README Blinkt! provides eight super-bright RGB LED indicators. Ideal for adding visual notifications to your Raspberry Pi. Learn more: https://shop.pimoroni.com/products/blinkt For examples run: `curl -sS get.pimoroni.com/blinkt | bash` ================================================ FILE: packaging/debian/changelog ================================================ blinkt (0.1.2) STABLE; urgency=low * BugFix: Added sleep to data output, see: https://github.com/pimoroni/blinkt/issues/62 -- Phil Howard Wed, 23 May 2018 00:00:00 +0000 blinkt (0.1.1) STABLE; urgency=low * New: Added `get_pixel` to return colour and brightness of a single pixel -- Phil Howard Tue, 20 Feb 2018 00:00:00 +0000 blinkt (0.1.0) STABLE; urgency=low * Removed try/except from RPi.GPIO import, output was misleading at best * Reverted default behaviour of clear on exit -- Phil Howard Tue, 06 Sep 2016 00:00:00 +0000 blinkt (0.0.9) UNRELEASED; urgency=low * Added set_all method to set all pixels * Changed default behaviour of clear on exit to reduce module side-effects * Move GPIO initialisation to show() to reduce module side-effects -- Phil Howard Tue, 06 Sep 2016 00:00:00 +0000 blinkt (0.0.8) UNRELEASED; urgency=low * Tweaked some methods to show intent as implementation detail only * Added docstrings detailing public methods -- Phil Howard Tue, 06 Sep 2016 00:00:00 +0000 blinkt (0.0.7) UNRELEASED; urgency=low * Fixed bug with APA102 pixels that have a small, black die (vs the larger, paler one) -- Phil Howard Wed, 24 Aug 2016 00:00:00 +0000 blinkt (0.0.6) UNRELEASED; urgency=low * set_clear_on_exit now method -- Phil Howard Thu, 11 Aug 2016 00:00:00 +0000 blinkt (0.0.5) UNRELEASED; urgency=low * Range clamping and coercion to integers -- Phil Howard Wed, 22 Jun 2016 00:00:00 +0000 blinkt (0.0.4) UNRELEASED; urgency=low * Various bug fixes -- Phil Howard Tue, 21 Jun 2016 18:00:00 +0000 blinkt (0.0.3) UNRELEASED; urgency=low * Switch to Python -- Phil Howard Tue, 21 Jun 2016 12:00:00 +0000 blinkt (0.0.2) UNRELEASED; urgency=low * Bug fixes for C Library -- Phil Howard Tue, 21 Jun 2016 06:00:00 +0000 blinkt (0.0.1) UNRELEASED; urgency=low * Original C Library -- Phil Howard Tue, 21 Jun 2016 00:00:00 +0000 ================================================ FILE: packaging/debian/clean ================================================ *.egg-info/* ================================================ FILE: packaging/debian/compat ================================================ 9 ================================================ FILE: packaging/debian/control ================================================ Source: blinkt Maintainer: Phil Howard Homepage: https://github.com/pimoroni/blinkt Section: python Priority: extra Build-Depends: debhelper (>= 9.0.0), dh-python, python-all (>= 2.7), python-setuptools, python3-all (>= 3.4), python3-setuptools Standards-Version: 3.9.6 X-Python-Version: >= 2.7 X-Python3-Version: >= 3.4 Package: python-blinkt Architecture: all Section: python Depends: ${misc:Depends}, ${python:Depends}, python-rpi.gpio Suggests: python-psutil, python-requests Description: Python library for the Pimoroni Blinkt! Blinkt! provides eight super-bright RGB LED indicators. Ideal for adding visual notifications to your Raspberry Pi. . This is the Python 2 version of the package. Package: python3-blinkt Architecture: all Section: python Depends: ${misc:Depends}, ${python3:Depends}, python3-rpi.gpio Suggests: python3-psutil, python3-requests Description: Python library for the Pimoroni Blinkt! Blinkt! provides eight super-bright RGB LED indicators. Ideal for adding visual notifications to your Raspberry Pi. . This is the Python 3 version of the package. ================================================ FILE: packaging/debian/copyright ================================================ Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: blinkt Source: https://github.com/pimoroni/blinkt Files: * Copyright: 2016 Pimoroni Ltd License: MIT License: MIT 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. ================================================ FILE: packaging/debian/docs ================================================ ================================================ FILE: packaging/debian/rules ================================================ #!/usr/bin/make -f # -*- makefile -*- #export DH_VERBOSE=1 export DH_OPTIONS %: dh $@ --with python2,python3 --buildsystem=python_distutils override_dh_auto_install: python setup.py install --root debian/python-blinkt --install-layout=deb python3 setup.py install --root debian/python3-blinkt --install-layout=deb ================================================ FILE: packaging/debian/source/format ================================================ 3.0 (native) ================================================ FILE: packaging/debian/source/options ================================================ extend-diff-ignore = "^[^/]+\.egg-info/" ================================================ FILE: packaging/makeall.sh ================================================ #!/bin/bash # script control variables reponame="" # leave this blank for auto-detection libname="" # leave this blank for auto-detection packagename="" # leave this blank for auto-selection debianlog="debian/changelog" debcontrol="debian/control" debcopyright="debian/copyright" debrules="debian/rules" debreadme="debian/README" debdir="$(pwd)" rootdir="$(dirname $debdir)" libdir="$rootdir/library" FLAG=false # function define success() { echo "$(tput setaf 2)$1$(tput sgr0)" } inform() { echo "$(tput setaf 6)$1$(tput sgr0)" } warning() { echo "$(tput setaf 1)$1$(tput sgr0)" } newline() { echo "" } # assessing repo and library variables if [ -z "$reponame" ] || [ -z "$libname" ]; then inform "detecting reponame and libname..." else inform "using reponame and libname overrides" fi if [ -z "$reponame" ]; then if [[ $rootdir == *"python"* ]]; then repodir="$(dirname $rootdir)" reponame="$(basename $repodir)" else repodir="$rootdir" reponame="$(basename $repodir)" fi reponame=$(echo "$reponame" | tr "[A-Z]" "[a-z]") fi if [ -z "$libname" ]; then cd "$libdir" libname=$(grep "name" setup.py | tr -d "[:space:]" | cut -c 7- | rev | cut -c 3- | rev) libname=$(echo "$libname" | tr "[A-Z]" "[a-z]") && cd "$debdir" fi if [ -z "$packagename" ]; then packagename="$libname" fi echo "reponame is $reponame and libname is $libname" echo "output packages will be python-$packagename and python3-$packagename" # checking generating changelog file ./makelog.sh version=$(head -n 1 "$libdir/CHANGELOG.txt") echo "building $libname version $version" # checking debian/changelog file inform "checking debian/changelog file..." if ! head -n 1 $debianlog | grep "$libname" &> /dev/null; then warning "library not mentioned in header!" && FLAG=true elif head -n 1 $debianlog | grep "UNRELEASED"; then warning "this changelog is not going to generate a release!" warning "change distribution to 'stable'" && FLAG=true fi # checking debian/copyright file inform "checking debian/copyright file..." if ! grep "^Source" $debcopyright | grep "$reponame" &> /dev/null; then warning "$(grep "^Source" $debcopyright)" && FLAG=true fi if ! grep "^Upstream-Name" $debcopyright | grep "$libname" &> /dev/null; then warning "$(grep "^Upstream-Name" $debcopyright)" && FLAG=true fi # checking debian/control file inform "checking debian/control file..." if ! grep "^Source" $debcontrol | grep "$libname" &> /dev/null; then warning "$(grep "^Source" $debcontrol)" && FLAG=true fi if ! grep "^Homepage" $debcontrol | grep "$reponame" &> /dev/null; then warning "$(grep "^Homepage" $debcontrol)" && FLAG=true fi if ! grep "^Package: python-$packagename" $debcontrol &> /dev/null; then warning "$(grep "^Package: python-" $debcontrol)" && FLAG=true fi if ! grep "^Package: python3-$packagename" $debcontrol &> /dev/null; then warning "$(grep "^Package: python3-" $debcontrol)" && FLAG=true fi if ! grep "^Priority: extra" $debcontrol &> /dev/null; then warning "$(grep "^Priority" $debcontrol)" && FLAG=true fi # checking debian/rules file inform "checking debian/rules file..." if ! grep "debian/python-$packagename" $debrules &> /dev/null; then warning "$(grep "debian/python-" $debrules)" && FLAG=true fi if ! grep "debian/python3-$packagename" $debrules &> /dev/null; then warning "$(grep "debian/python3-" $debrules)" && FLAG=true fi # checking debian/README file inform "checking debian/readme file..." if ! grep -e "$libname" -e "$reponame" $debreadme &> /dev/null; then warning "README does not seem to mention product, repo or lib!" && FLAG=true fi # summary of checks pre build if $FLAG; then warning "Check all of the above and correct!" && exit 1 else inform "we're good to go... bulding!" fi # building deb and final checks ./makedeb.sh inform "running lintian..." lintian -v $(find -name "python*$version*.deb") lintian -v $(find -name "python3*$version*.deb") inform "checking signatures..." gpg --verify $(find -name "*$version*changes") gpg --verify $(find -name "*$version*dsc") exit 0 ================================================ FILE: packaging/makedeb.sh ================================================ #!/bin/bash gettools="no" # if set to yes downloads the tools required setup="yes" # if set to yes populates library folder buildeb="yes" # if set to yes builds the deb files cleanup="yes" # if set to yes cleans up build files pkgfiles=( "build" "changes" "deb" "dsc" "tar.xz" ) if [ $gettools == "yes" ]; then sudo apt-get update && sudo apt-get install build-essential debhelper devscripts dh-make dh-python dput gnupg sudo apt-get install python-all python-setuptools python3-all python3-setuptools sudo apt-get install python-mock python-sphinx python-sphinx-rtd-theme sudo pip install Sphinx --upgrade && sudo pip install sphinx_rtd_theme --upgrade fi if [ $setup == "yes" ]; then rm -R ../library/build ../library/debian &> /dev/null cp -R ./debian ../library/ && cp -R ../sphinx ../library/doc fi cd ../library if [ $buildeb == "yes" ]; then debuild -aarmhf for file in ${pkgfiles[@]}; do rm ../packaging/*.$file &> /dev/null mv ../*.$file ../packaging done rm -R ../documentation/html &> /dev/null cp -R ./build/sphinx/html ../documentation fi if [ $cleanup == "yes" ]; then debuild clean rm -R ./build ./debian ./doc &> /dev/null fi exit 0 ================================================ FILE: packaging/makedoc.sh ================================================ #!/bin/bash gettools="no" # if set to yes downloads the tools required setup="yes" # if set to yes populates library folder buildoc="yes" # if set to yes builds the deb files cleanup="yes" # if set to yes cleans up build files pkgfiles=( "build" "changes" "deb" "dsc" "tar.xz" ) if [ $gettools == "yes" ]; then sudo apt-get update && sudo apt-get install build-essential debhelper devscripts dh-make dh-python sudo apt-get install python-all python-setuptools python3-all python3-setuptools sudo apt-get install python-mock python-sphinx python-sphinx-rtd-theme sudo pip install Sphinx --upgrade && sudo pip install sphinx_rtd_theme --upgrade fi if [ $setup == "yes" ]; then rm -R ../library/build ../library/debian &> /dev/null cp -R ./debian ../library/ && cp -R ../sphinx ../library/doc fi cd ../library if [ $buildoc == "yes" ]; then debuild for file in ${pkgfiles[@]}; do rm ../*.$file &> /dev/null done rm -R ../documentation/html &> /dev/null cp -R ./build/sphinx/html ../documentation fi if [ $cleanup == "yes" ]; then debuild clean rm -R ./build ./debian ./doc &> /dev/null fi exit 0 ================================================ FILE: packaging/makelog.sh ================================================ #!/bin/bash # script control variables libname="" # leave this blank for auto-detection sibname=() # name of sibling in packages list versionwarn="yes" # set to anything but 'yes' to turn off warning debdir="$(pwd)" rootdir="$(dirname $debdir)" libdir="$rootdir/library" mainlog="CHANGELOG" debianlog="debian/changelog" pypilog="$libdir/CHANGELOG.txt" # function define success() { echo "$(tput setaf 2)$1$(tput sgr0)" } inform() { echo "$(tput setaf 6)$1$(tput sgr0)" } warning() { echo "$(tput setaf 1)$1$(tput sgr0)" } newline() { echo "" } # generate debian changelog cat $mainlog > $debianlog inform "seeded debian changelog" # generate pypi changelog sed -e "/--/d" -e "s/ \*/\*/" \ -e "s/.*\([0-9].[0-9].[0-9]\).*/\1/" \ -e '/[0-9].[0-9].[0-9]/ a\ -----' $mainlog | cat -s > $pypilog version=$(head -n 1 $pypilog) inform "pypi changelog generated" # touch up version in setup.py file if [ -n $(grep version "$libdir/setup.py" &> /dev/null) ]; then inform "touched up version in setup.py" sed -i "s/'[0-9].[0-9].[0-9]'/'$version'/" "$libdir/setup.py" else warning "couldn't touch up version in setup, no match found" fi # touch up version in lib or package siblings if [ -z "$libname" ]; then cd "$libdir" libname=$(grep "name" setup.py | tr -d "[:space:]" | cut -c 7- | rev | cut -c 3- | rev) libname=$(echo "$libname" | tr "[A-Z]" "[a-z]") && cd "$debdir" sibname+=( "$libname" ) elif [ "$libname" != "package" ]; then sibname+=( "$libname" ) fi for sibling in ${sibname[@]}; do if grep -e "__version__" "$libdir/$sibling.py" &> /dev/null; then sed -i "s/__version__ = '[0-9].[0-9].[0-9]'/__version__ = '$version'/" "$libdir/$sibling.py" inform "touched up version in $sibling.py" elif grep -e "__version__" "$libdir/$sibling/__init__.py" &> /dev/null; then sed -i "s/__version__ = '[0-9].[0-9].[0-9]'/__version__ = '$version'/" "$libdir/$sibling/__init__.py" inform "touched up version in $sibling/__init__.py" elif [ "$versionwarn" == "yes" ]; then warning "couldn't touch up __version__ in $sibling, no match found" fi done exit 0 ================================================ FILE: projects/mqtt/mqtt.py ================================================ #!/usr/bin/env python from sys import exit import argparse import time try: import paho.mqtt.client as mqtt except ImportError: raise ImportError("This example requires the paho-mqtt module\nInstall with: sudo pip install paho-mqtt") import blinkt MQTT_SERVER = "localhost" MQTT_PORT = 1883 MQTT_TOPIC = "pimoroni/blinkt" # Set these to use authorisation MQTT_USER = None MQTT_PASS = None description = """\ MQTT Blinkt! Control This example uses MQTT messages from {server} on port {port} to control Blinkt! It will monitor the {topic} topic by default, and understands the following messages: rgb,,,, - Set a single pixel to an RGB colour. Example: rgb,1,255,0,255 clr - Clear Blinkt! bri, - Set global brightness (for val in range 0.0-1.0) You can use the online MQTT tester at http://www.hivemq.com/demos/websocket-client/ to send messages. Use {server} as the host, and port 80 (Eclipse's websocket port). Set the topic to topic: {topic} """.format( server=MQTT_SERVER, port=MQTT_PORT, topic=MQTT_TOPIC ) parser = argparse.ArgumentParser(description=description, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-H', '--host', default=MQTT_SERVER, help='MQTT broker to connect to') parser.add_argument('-P', '--port', default=MQTT_PORT, type=int, help='port on MQTT broker to connect to') parser.add_argument('-T', '--topic', action='append', help='MQTT topic to subscribe to; can be repeated for multiple topics') parser.add_argument('-u', '--user', help='MQTT broker user name') parser.add_argument('-p', '--pass', dest='pw', help='MQTT broker password') parser.add_argument('-q', '--quiet', default=False, action='store_true', help='Minimal output (eg for running as a daemon)') parser.add_argument('-g', '--green-hack', default=False, action='store_true', help='Apply hack to green channel to improve colour saturation') parser.add_argument('--timeout', default='0', help='Pixel timeout(s). Pixel will blank if last update older than X seconds. May be a single number or comma-separated list. Use 0 for no timeout') parser.add_argument('-D', '--daemon', metavar='PIDFILE', help='Run as a daemon (implies -q)') args = parser.parse_args() # Get timeout list into expected form args.timeout = args.timeout.split(',') if len(args.timeout) == 1: args.timeout = args.timeout * blinkt.NUM_PIXELS elif len(args.timeout) != blinkt.NUM_PIXELS: print("--timeout list must be {} elements long".format(blinkt.NUM_PIXELS)) exit(1) try: args.timeout = [int(x) for x in args.timeout] except ValueError as e: print("Bad timeout value: {}".format(e)) exit(1) args.timeout = [x and x or 0 for x in args.timeout] args.min_timeout = min(args.timeout) if args.daemon: import signal try: import daemon except ImportError: raise ImportError("--daemon requires the daemon module. Install with: sudo pip install python-daemon") try: import lockfile.pidlockfile except ImportError: raise ImportError("--daemon requires the lockfile module. Install with: sudo pip install lockfile") if not args.topic: args.topic = [MQTT_TOPIC] class PixelClient(mqtt.Client): def __init__(self, prog_args, *args, **kwargs): super(PixelClient, self).__init__(*args, **kwargs) self.args = prog_args self.update_time = [None] * blinkt.NUM_PIXELS self.on_connect = self.on_connect self.on_message = self.on_message blinkt.set_clear_on_exit() # Some stuff doesn't get set up until the first time show() is called blinkt.show() if self.args.user is not None and self.args.pw is not None: self.username_pw_set(username=self.args.user, password=self.args.pw) self.connect(self.args.host, self.args.port, 60) def cmd_clear(self): blinkt.clear() blinkt.show() def cmd_brightness(self, bri): try: bri = float(bri) except ValueError: print("Malformed command brightness, expected float, got: {}".format(str(bri))) return blinkt.set_brightness(bri) blinkt.show() def cmd_rgb(self, pixel, data): try: if pixel == "*": pixel = None else: pixel = int(pixel) if pixel > 7: print("Pixel out of range: {}".format(str(pixel))) return r, g, b = [int(x) & 0xff for x in data] if self.args.green_hack: # Green is about twice the luminosity for a given value # than red or blue, so apply a hackish linear compensation # here taking care of corner cases at 0 and 255. To do it # properly, it should really be a curve but this approximation # is quite a lot better than nothing. if r not in [0, 255]: r = r + 1 if g not in [0]: g = g / 2 + 1 if b not in [0, 255]: b = b + 1 if not self.args.quiet: print('rgb', pixel, r, g, b) except ValueError: print("Malformed RGB command: {} {}".format(str(pixel), str(data))) return if pixel is None: for x in range(blinkt.NUM_PIXELS): blinkt.set_pixel(x, r, g, b) self.update_time[x] = time.time() else: blinkt.set_pixel(pixel, r, g, b) self.update_time[pixel] = time.time() blinkt.show() def on_connect(self, client, userdata, flags, rc): if not self.args.quiet: print("Connected to {s}:{p} listening for topics {t} with result code {r}.\nSee {c} --help for options.".format( s=self.args.host, p=self.args.port, t=', '.join(self.args.topic), r=rc, c=parser.prog )) for topic in self.args.topic: client.subscribe(topic) def on_message(self, client, userdata, msg): data = msg.payload.decode('utf-8').strip().split(',') command = data.pop(0) print(command, data) if command == "clr" and len(data) == 0: self.cmd_clear() return if command == "bri" and len(data) == 1: self.cmd_brightness(data[0]) return if command == "rgb" and len(data) == 4: self.cmd_rgb(data[0], data[1:]) return def blank_timed_out_pixels(self): now = time.time() to_upt_pairs = zip(self.args.timeout, self.update_time) for pixel, (to, uptime) in enumerate(to_upt_pairs): if to is not None and uptime is not None and uptime < now - to: blinkt.set_pixel(pixel, 0, 0, 0) self.update_time[pixel] = None blinkt.show() def loop(self, timeout=1.0, max_packets=1): self.blank_timed_out_pixels() return super(PixelClient, self).loop(timeout, max_packets) def sigterm(signum, frame): client._thread_terminate = True if args.daemon: # Monkey-patch daemon so's the daemon starts reasonably quickly. FDs don't # strictly speaking need closing anyway because we haven't opened any (yet). daemon.daemon.get_maximum_file_descriptors = lambda: 32 args.quiet = True pidlf = lockfile.pidlockfile.PIDLockFile(args.daemon) with daemon.DaemonContext( pidfile=pidlf, signal_map={signal.SIGTERM: sigterm}): client = PixelClient(args) client.loop_forever() else: client = PixelClient(args) client.loop_forever() ================================================ FILE: sphinx/_static/custom.css ================================================ .rst-content a, .rst-content a:focus { color:#13c0d7; } .rst-content a:visited, .rst-content a:active { color:#87319a; } .rst-content .highlighted { background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAJElEQVQIW2P8//9/PSMjYyMDEmAEsdElwILoEnBBZAkUQZgEABMWE4Kzp1KUAAAAAElFTkSuQmCC),rgba(246,167,4,0.2); } .wy-side-nav-search { background:#333333; } .wy-nav-side { background:#444444; } .rst-content dl:not(.docutils) dt { background:#e7fafd; border-top:solid 3px #13c0d7; color:rgba(0,0,0,0.5); } .rst-content .viewcode-link, .rst-content .viewcode-back { color:#00b09b; } code.literal { color:#e63c2e; } .rst-content #module-blinkt { margin-bottom:24px; } .rst-content #module-blinkt dl:not(.docutils) dt { border:none; background:#f0f0f0; } .rst-content #module-blinkt dl:not(.docutils) dd { display:none; } .rst-content #module-blinkt dl:not(.docutils) { margin-bottom:0; } ================================================ FILE: sphinx/_templates/breadcrumbs.html ================================================ ================================================ FILE: sphinx/_templates/layout.html ================================================ {% extends "!layout.html" %} {% block extrahead %} {% endblock %} ================================================ FILE: sphinx/conf.py ================================================ #-*- coding: utf-8 -*- import sys import site import mock PACKAGE_NAME = u"Blinkt!" PACKAGE_HANDLE = "Blinkt" PACKAGE_MODULE = "blinkt" # Prompte /usr/local/lib to the front of sys.path #sys.path.insert(0,site.getsitepackages()[0]) import sphinx_rtd_theme sys.modules['RPi'] = mock.Mock() sys.modules['RPi.GPIO'] = mock.Mock() sys.path.insert(0, '../library/') import blinkt from sphinx.ext import autodoc class OutlineMethodDocumenter(autodoc.MethodDocumenter): objtype = 'method' def add_content(self, more_content, no_docstring=False): return class OutlineFunctionDocumenter(autodoc.FunctionDocumenter): objtype = 'function' def add_content(self, more_content, no_docstring=False): return class ModuleOutlineDocumenter(autodoc.ModuleDocumenter): objtype = 'moduleoutline' def __init__(self, directive, name, indent=u''): # Monkey path the Method and Function documenters sphinx_app.add_autodocumenter(OutlineMethodDocumenter) sphinx_app.add_autodocumenter(OutlineFunctionDocumenter) autodoc.ModuleDocumenter.__init__(self, directive, name, indent) def __del__(self): # Return the Method and Function documenters to normal sphinx_app.add_autodocumenter(autodoc.MethodDocumenter) sphinx_app.add_autodocumenter(autodoc.FunctionDocumenter) def setup(app): global sphinx_app sphinx_app = app app.add_autodocumenter(ModuleOutlineDocumenter) ModuleOutlineDocumenter.objtype = 'module' # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. # # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = PACKAGE_NAME copyright = u'2017, Pimoroni Ltd' author = u'Phil Howard' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = u'{}'.format(blinkt.__version__) # The full version, including alpha/beta/rc tags. release = u'{}'.format(blinkt.__version__) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # # today = '' # # Else, today_fmt is used as the format for a strftime call. # # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The reST default role (used for this markup: `text`) to use for all # documents. # # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' #html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = { 'collapse_navigation': False, 'display_version': True } # Add any paths that contain custom themes here, relative to this directory. html_theme_path = [ '_themes', sphinx_rtd_theme.get_html_theme_path() ] # The name for this set of Sphinx documents. # " v documentation" by default. # # html_title = PACKAGE_NAME + u' v0.1.2' # A shorter title for the navigation bar. Default is the same as html_title. # # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = 'shop-logo.png' # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = 'favicon.png' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # # html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. # # html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # # html_additional_pages = {} # If false, no module index is generated. # # html_domain_indices = True # If false, no index is generated. # html_use_index = False # If true, the index is split into individual pages for each letter. # # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = False # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' # # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `jieba` dictionary path. # # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = PACKAGE_HANDLE + 'doc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, PACKAGE_HANDLE + '.tex', PACKAGE_NAME + u' Documentation', u'Phil Howard', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # # latex_use_parts = False # If true, show page references after internal links. # # latex_show_pagerefs = False # If true, show URL addresses after external links. # # latex_show_urls = False # Documents to append as an appendix to all manuals. # # latex_appendices = [] # It false, will not define \strong, \code, itleref, \crossref ... but only # \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added # packages. # # latex_keep_old_macro_names = True # If false, no module index is generated. # # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, PACKAGE_MODULE, PACKAGE_NAME + u' Documentation', [author], 1) ] # If true, show URL addresses after external links. # # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, PACKAGE_HANDLE, PACKAGE_NAME + u' Documentation', author, PACKAGE_HANDLE, 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # # texinfo_appendices = [] # If false, no module index is generated. # # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # # texinfo_no_detailmenu = False ================================================ FILE: sphinx/index.rst ================================================ .. role:: python(code) :language: python .. toctree:: :titlesonly: :maxdepth: 0 Welcome ------- This documentation will guide you through the methods available in the Blinkt! python library. Blinkt! is a tiny Raspberry Pi add-on with 8, APA102, RGB LEDs which you can drive independently for notifications, lighting effects, animation effects and more! * More information - https://shop.pimoroni.com/products/blinkt * Get the code - https://github.com/pimoroni/blinkt * Get started - https://learn.pimoroni.com/tutorial/sandyj/getting-started-with-blinkt * Get help - http://forums.pimoroni.com/c/support At A Glance ----------- .. automoduleoutline:: blinkt :members: Set A Single Pixel ------------------ The bread and butter of Blintk! is setting pixels. You can set any of the 8 pixels on your Blinkt! to one of around 16 million colours! The :python:`brightness` argument is completely optional. Omit it to keep the last brightness value set for that particular pixel. .. automodule:: blinkt :noindex: :members: set_pixel Set All Pixels -------------- Sometimes you need to set all the pixels to the same colour. This convinience method does just that! .. automodule:: blinkt :noindex: :members: set_all Show ---- None of your pixels will appear on Blinkt! until you :python:`show()` them. This method writes all the pixel data out to your device. .. automodule:: blinkt :noindex: :members: show Clear ----- Exactly the same as calling :python:`set_all(0,0,0)`, clear sets all the pixels to black. You must also call :python:`show()` if you want to turn Blinkt! off. .. automodule:: blinkt :noindex: :members: clear Enable/Disable Clear On Exit ---------------------------- Sometimes you want a script that runs and quits, leaving a pattern up on Blinkt! .. automodule:: blinkt :noindex: :members: set_clear_on_exit Get A Single Pixel ------------------ .. automodule:: blinkt :noindex: :members: get_pixel Constants --------- Blinkt! has 8 pixels. Simple. Use the constant :python:`blinkt.NUM_PIXELS` when you're iterating over pixels, so you can avoid a *magic number* in your code. :python:`blinkt.NUM_PIXELS = 8`