./0000755000175000017500000000000014223645756012155 5ustar jawn-smithjawn-smith./library/0000775000175000017500000000000014223621661013610 5ustar jawn-smithjawn-smith./library/test/0000775000175000017500000000000014223621661014567 5ustar jawn-smithjawn-smith./library/test/README.txt0000664000175000017500000000000014223621661016253 0ustar jawn-smithjawn-smith./library/test/README.md0000664000175000017500000000000014223621661016034 0ustar jawn-smithjawn-smith./library/test/MANIFEST.in0000664000175000017500000000017014223621661016323 0ustar jawn-smithjawn-smithinclude CHANGELOG.txt include LICENSE.txt include README.txt include LICENSE.txt include setup.py include UnicornHat.py ./library/test/setup.py0000775000175000017500000000102614223621661016303 0ustar jawn-smithjawn-smith#!/usr/bin/env python try: from setuptools import setup, find_packages, Extension except ImportError: from distutils.core import setup, find_packages, Extension setup( name = 'Unicorn Hat', version = '1.0.0', author = 'Philip Howard', author_email = 'phil@pimoroni.com', url = '', description = """Python library for Unicorn HAT""", long_description=open('README.txt').read() + open('CHANGELOG.txt').read(), py_modules = [ 'UnicornHat' ] ) ./library/test/CHANGELOG.txt0000664000175000017500000000000014223621661016605 0ustar jawn-smithjawn-smith./library/test/UnicornHat_Emulator.py0000775000175000017500000001174314223621661021074 0ustar jawn-smithjawn-smith#!/usr/bin/env python import Queue import signal import socket import threading import time from sys import exit, version_info try: from Tkinter import Canvas, Frame, Tk except ImportError: if version_info[0] < 3: exit("This library requires python-tk\nInstall with: sudo apt-get install python-tk") elif version_info[0] == 3: exit("This library requires python3-tk\nInstall with: sudo apt-get install python3-tk") PIXELS_X = 8 PIXELS_Y = 8 PIXEL_SPACING = 5 PIXEL_W = 10 PIXEL_H = 10 BORDER = 10 DISPLAY_W = ((PIXEL_W + PIXEL_SPACING) * PIXELS_X) - PIXEL_SPACING + (BORDER * 2) DISPLAY_H = ((PIXEL_H + PIXEL_SPACING) * PIXELS_Y) - PIXEL_SPACING + (BORDER * 2) window = None display = None class Display(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.canvas = None self.buffer = {} self.pixels = {} self.pack() self.init_display() def init_display(self): self.canvas = Canvas(self.master, width=DISPLAY_W, height=DISPLAY_H, bg='white') self.canvas.pack() for x in range(PIXELS_X): for y in range(PIXELS_Y): pixel_x = ((PIXEL_W + PIXEL_SPACING) * x) + BORDER pixel_y = ((PIXEL_H + PIXEL_SPACING) * y) + BORDER self.buffer[ (x,y) ] = [0,0,0] self.pixels[ (x,y) ] = self.canvas.create_rectangle(pixel_x, pixel_y, pixel_x + PIXEL_W, pixel_y + PIXEL_H, fill='black', width=0) def set_pixel(self,x, y, r, g, b): self.buffer[ (x,y) ] = [r,g,b] def clear(): # Clear the display for x in range(8): for x in range(8): self.set_pixel(x,y,0,0,0) self.show() def show_q(self, pixels): x = 0 for idx,pixel in enumerate(pixels): x = idx % 8 y = int(idx / 8) self.canvas.itemconfigure(self.pixels[(x,y)], fill= '#' + pixel) x+=1 def show(self): for position, colour in self.buffer.iteritems(): pixel = self.pixels[ position ] r = hex(colour[0])[2:].zfill(2) g = hex(colour[1])[2:].zfill(2) b = hex(colour[2])[2:].zfill(2) self.canvas.itemconfigure(pixel, fill= '#' + r + g + b) queue = Queue.Queue() ## Basic stoppable thread wrapper # # Adds Event for stopping the execution loop # and exiting cleanly. class StoppableThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.stop_event = threading.Event() self.daemon = True def start(self): if self.isAlive() == False: self.stop_event.clear() threading.Thread.start(self) def stop(self): if self.isAlive() == True: # set event to signal thread to terminate self.stop_event.set() # block calling thread until thread really has terminated self.join() ## Basic thread wrapper class for asyncronously running functions # # Basic thread wrapper class for running functions # asyncronously. Return False from your function # to abort looping. class AsyncWorker(StoppableThread): def __init__(self, todo): StoppableThread.__init__(self) self.todo = todo def run(self): while self.stop_event.is_set() == False: if self.todo() == False: self.stop_event.set() break def tcp(): global buf, queue, client if client == None: try: client = sck.accept() except: pass if client != None: char = None try: char = client[0].recv(1) except: pass if char != None: if char == '\n': message = ''.join(buf).strip() if message == 'stop': client = None else: queue.put(message) buf = [] else: buf.append(char) return True buf = [] client = None window = Tk() display = Display(window) def processqueue(): try: message = None while queue.qsize() > 1: message = queue.get_nowait() if message != None: if message == 'show': display.show() elif message == 'clear': display.clear() else: message = message.split(',') display.show_q(message) ##display.set_pixel(int(message[0]),int(message[1]),int(message[2]),int(message[3]),int(message[4])) except Queue.Empty: pass window.after(5, processqueue) window.after(5, processqueue) sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.settimeout(0) port = 7676 bound = False while not bound: try: sck.bind(('127.0.0.1',port)) bound = True print("Bound to",port) except socket.error: port+=1 sck.listen(50) t_setup = AsyncWorker(tcp) t_setup.start() display.mainloop() ./library/test/UnicornHat.py0000775000175000017500000000174714223621661017227 0ustar jawn-smithjawn-smithimport atexit import socket import time sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print('Unicorn Started') connected = False port = 7676 pixels = ['000000'] * 64 attempt = 0 while not connected: try: time.sleep(0.5) print('Trying port',port + attempt) sck.connect(('127.0.0.1',port + attempt)) connected = True print('Connected',port + attempt) except: if attempt >= 10: exit("Unable to connect to UnicornHat Emulator") attempt += 1 def close(): send('stop') sck.shutdown(socket.SHUT_RDWR) sck.close() atexit.register(close) def send(cmd): print(cmd); sck.send(cmd + '\n') def clear(): send('clear') def set_pixel(x, y, r, g, b): r = hex(r)[2:].zfill(2) g = hex(g)[2:].zfill(2) b = hex(b)[2:].zfill(2) pixels[(x*8) + y] = ''.join([r,g,b]) #send( ','.join([str(x),str(y),str(r),str(g),str(b)]) ) def show(): #send('show') send(','.join(pixels)) ./library/test/LICENSE.txt0000664000175000017500000000205614223621661016415 0ustar jawn-smithjawn-smithMIT 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. ./library/legacy/0000775000175000017500000000000014223621661015054 5ustar jawn-smithjawn-smith./library/legacy/ws2812/0000775000175000017500000000000014223621661016022 5ustar jawn-smithjawn-smith./library/legacy/ws2812/ws2812-RPi.i0000664000175000017500000000325414223621661017636 0ustar jawn-smithjawn-smith%module ws2812 %{ #include "lib/ws2812-RPi.h" %} %typemap(in) (unsigned char *data, int len) { $1 = (unsigned char *) PyString_AsString($input); $2 = PyString_Size($input); }; %apply unsigned char { uint8_t }; typedef struct { unsigned char r; unsigned char g; unsigned char b; } Color_t; extern void init(int numPixels); extern void clear(void); extern void show(void); extern Color_t Wheel(uint8_t WheelPos); extern void colorWipe(Color_t c, uint8_t wait); extern void rainbow(uint8_t wait); extern void rainbowCycle(uint8_t wait); extern void theaterChase(Color_t c, uint8_t wait); extern void theaterChaseRainbow(uint8_t wait); extern unsigned char setBrightness(double b); extern double getBrightness(); extern Color_t RGB2Color(unsigned char r, unsigned char g, unsigned char b); extern Color_t Color(unsigned char r, unsigned char g, unsigned char b); extern unsigned char setPixelColor(unsigned int pixel, unsigned char r, unsigned char g, unsigned char b); extern unsigned char setPixelColorT(unsigned int pixel, Color_t c); extern Color_t getPixelColor(unsigned int pixel); extern unsigned int numPixels(void); extern Color_t* getPixels(void); extern void setPWMBit(unsigned int bitPos, unsigned char bit); extern unsigned char getPWMBit(unsigned int bitPos); extern void dumpLEDBuffer(void); extern void dumpPWMBuffer(void); extern void dumpPWMStatus(void); extern void dumpPWMControl(unsigned int word); extern void dumpPWMDMAC(void); extern void dumpPWM(void); extern void dumpDMARegs(void); extern void dumpControlBlock(dma_cb_t *c); extern void dumpTransferInformation(unsigned int TI); extern void dumpDMA(void); extern void terminate(int dummy); ./library/legacy/ws2812/ws2812.py0000664000175000017500000001364714223621661017355 0ustar jawn-smithjawn-smith# This file was automatically generated by SWIG (http://www.swig.org). # Version 2.0.7 # # 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('_ws2812', [dirname(__file__)]) except ImportError: import _ws2812 return _ws2812 if fp is not None: try: _mod = imp.load_module('_ws2812', fp, pathname, description) finally: fp.close() return _mod _ws2812 = swig_import_helper() del swig_import_helper else: import _ws2812 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 class Color_t(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, Color_t, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, Color_t, name) __repr__ = _swig_repr __swig_setmethods__["r"] = _ws2812.Color_t_r_set __swig_getmethods__["r"] = _ws2812.Color_t_r_get if _newclass:r = _swig_property(_ws2812.Color_t_r_get, _ws2812.Color_t_r_set) __swig_setmethods__["g"] = _ws2812.Color_t_g_set __swig_getmethods__["g"] = _ws2812.Color_t_g_get if _newclass:g = _swig_property(_ws2812.Color_t_g_get, _ws2812.Color_t_g_set) __swig_setmethods__["b"] = _ws2812.Color_t_b_set __swig_getmethods__["b"] = _ws2812.Color_t_b_get if _newclass:b = _swig_property(_ws2812.Color_t_b_get, _ws2812.Color_t_b_set) def __init__(self): this = _ws2812.new_Color_t() try: self.this.append(this) except: self.this = this __swig_destroy__ = _ws2812.delete_Color_t __del__ = lambda self : None; Color_t_swigregister = _ws2812.Color_t_swigregister Color_t_swigregister(Color_t) def init(*args): return _ws2812.init(*args) init = _ws2812.init def clear(): return _ws2812.clear() clear = _ws2812.clear def show(): return _ws2812.show() show = _ws2812.show def Wheel(*args): return _ws2812.Wheel(*args) Wheel = _ws2812.Wheel def colorWipe(*args): return _ws2812.colorWipe(*args) colorWipe = _ws2812.colorWipe def rainbow(*args): return _ws2812.rainbow(*args) rainbow = _ws2812.rainbow def rainbowCycle(*args): return _ws2812.rainbowCycle(*args) rainbowCycle = _ws2812.rainbowCycle def theaterChase(*args): return _ws2812.theaterChase(*args) theaterChase = _ws2812.theaterChase def theaterChaseRainbow(*args): return _ws2812.theaterChaseRainbow(*args) theaterChaseRainbow = _ws2812.theaterChaseRainbow def setBrightness(*args): return _ws2812.setBrightness(*args) setBrightness = _ws2812.setBrightness def getBrightness(): return _ws2812.getBrightness() getBrightness = _ws2812.getBrightness def RGB2Color(*args): return _ws2812.RGB2Color(*args) RGB2Color = _ws2812.RGB2Color def Color(*args): return _ws2812.Color(*args) Color = _ws2812.Color def setPixelColor(*args): return _ws2812.setPixelColor(*args) setPixelColor = _ws2812.setPixelColor def setPixelColorT(*args): return _ws2812.setPixelColorT(*args) setPixelColorT = _ws2812.setPixelColorT def getPixelColor(*args): return _ws2812.getPixelColor(*args) getPixelColor = _ws2812.getPixelColor def numPixels(): return _ws2812.numPixels() numPixels = _ws2812.numPixels def getPixels(): return _ws2812.getPixels() getPixels = _ws2812.getPixels def setPWMBit(*args): return _ws2812.setPWMBit(*args) setPWMBit = _ws2812.setPWMBit def getPWMBit(*args): return _ws2812.getPWMBit(*args) getPWMBit = _ws2812.getPWMBit def dumpLEDBuffer(): return _ws2812.dumpLEDBuffer() dumpLEDBuffer = _ws2812.dumpLEDBuffer def dumpPWMBuffer(): return _ws2812.dumpPWMBuffer() dumpPWMBuffer = _ws2812.dumpPWMBuffer def dumpPWMStatus(): return _ws2812.dumpPWMStatus() dumpPWMStatus = _ws2812.dumpPWMStatus def dumpPWMControl(*args): return _ws2812.dumpPWMControl(*args) dumpPWMControl = _ws2812.dumpPWMControl def dumpPWMDMAC(): return _ws2812.dumpPWMDMAC() dumpPWMDMAC = _ws2812.dumpPWMDMAC def dumpPWM(): return _ws2812.dumpPWM() dumpPWM = _ws2812.dumpPWM def dumpDMARegs(): return _ws2812.dumpDMARegs() dumpDMARegs = _ws2812.dumpDMARegs def dumpControlBlock(*args): return _ws2812.dumpControlBlock(*args) dumpControlBlock = _ws2812.dumpControlBlock def dumpTransferInformation(*args): return _ws2812.dumpTransferInformation(*args) dumpTransferInformation = _ws2812.dumpTransferInformation def dumpDMA(): return _ws2812.dumpDMA() dumpDMA = _ws2812.dumpDMA def terminate(*args): return _ws2812.terminate(*args) terminate = _ws2812.terminate # This file is compatible with both classic and new-style classes. ./library/legacy/ws2812/README0000664000175000017500000000000014223621661016670 0ustar jawn-smithjawn-smith./library/legacy/ws2812/MANIFEST.in0000664000175000017500000000022014223621661017552 0ustar jawn-smithjawn-smithinclude ws2812.py include ws2812-RPi.h include ws2812-RPi.c include README include README.md include LICENSE.txt include setup.py include lib/* ./library/legacy/ws2812/ws2812-RPi_wrap.c0000664000175000017500000043077014223621661020670 0ustar jawn-smithjawn-smith/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.7 * * 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 /* Python.h has to appear first */ #include /* ----------------------------------------------------------------------------- * 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 # 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 not equal, 1 if equal */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { int equiv = 0; const char* te = tb + strlen(tb); const char* ne = nb; while (!equiv && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; if (*ne) ++ne; } return equiv; } /* Check type equivalence in a name list like ||... Return 0 if equal, -1 if nb < tb, 1 if nb > tb */ SWIGRUNTIME int SWIG_TypeCompare(const char *nb, const char *tb) { int equiv = 0; const char* te = tb + strlen(tb); const char* ne = nb; while (!equiv && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; if (*ne) ++ne; } return equiv; } /* 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) { register size_t l = 0; register size_t r = iter->size - 1; do { /* since l+r >= 0, we can (>> 1) instead (/ 2) */ register size_t i = (l + r) >> 1; const char *iname = iter->types[i]->name; if (iname) { register 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 { register 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"; register const unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register 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) { register unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register char d = *(c++); register 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 < 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() #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) { register 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 { register 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 { register 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_print(SwigPyObject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { char *str; #ifdef METH_NOARGS PyObject *repr = SwigPyObject_repr(v); #else PyObject *repr = SwigPyObject_repr(v, NULL); #endif if (repr) { str = SWIG_Python_str_AsChar(repr); fputs(str, fp); SWIG_Python_str_DelForPy3(str); Py_DECREF(repr); return 0; } else { return 1; } } SWIGRUNTIME PyObject * SwigPyObject_str(SwigPyObject *v) { char result[SWIG_BUFFER_SIZE]; return SWIG_PackVoidPtr(result, v->ptr, v->ty->name, sizeof(result)) ? SWIG_Python_str_FromChar(result) : 0; } 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 *)"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_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 */ (printfunc)SwigPyObject_print, /* 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 */ (reprfunc)SwigPyObject_str, /* 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; if (!obj) return SWIG_ERROR; if (obj == Py_None) { 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 (flags & SWIG_POINTER_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); } } } } } 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 = PyBaseObject_Type.tp_new((PyTypeObject*) data->newargs, Py_None, Py_None); PyObject_SetAttr(inst, SWIG_This(), swig_this); Py_TYPE(inst)->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; #else PyObject *dict = PyDict_New(); 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; PyObject *dict = PyDict_New(); 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 (clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); if (inst) { 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) { 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_Python_GetModule(); 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; # 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; } res = -1; 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_Color_t swig_types[0] #define SWIGTYPE_p_char swig_types[1] #define SWIGTYPE_p_dma_cb_t swig_types[2] static swig_type_info *swig_types[4]; static swig_module_info swig_module = {swig_types, 3, 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):= _ws2812.so ------------------------------------------------*/ #if PY_VERSION_HEX >= 0x03000000 # define SWIG_init PyInit__ws2812 #else # define SWIG_init init_ws2812 #endif #define SWIG_name "_ws2812" #define SWIGVERSION 0x020007 #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 "lib/ws2812-RPi.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 (PyInt_Check(obj)) { long v = PyInt_AsLong(obj); if (v >= 0) { if (val) *val = v; return SWIG_OK; } else { return SWIG_OverflowError; } } else if (PyLong_Check(obj)) { unsigned long v = PyLong_AsUnsignedLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } #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; } #define SWIG_From_long PyLong_FromLong SWIGINTERNINLINE PyObject* SWIG_From_unsigned_SS_long (unsigned long value) { return (value > LONG_MAX) ? PyLong_FromUnsignedLong(value) : PyLong_FromLong((long)(value)); } SWIGINTERNINLINE PyObject * SWIG_From_unsigned_SS_char (unsigned char value) { return SWIG_From_unsigned_SS_long (value); } SWIGINTERN int SWIG_AsVal_long (PyObject *obj, long* val) { if (PyInt_Check(obj)) { if (val) *val = PyInt_AsLong(obj); return SWIG_OK; } else if (PyLong_Check(obj)) { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } #ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; long v = PyInt_AsLong(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, LONG_MIN, LONG_MAX)) { if (val) *val = (long)(d); return res; } } } #endif return SWIG_TypeError; } SWIGINTERN int SWIG_AsVal_int (PyObject * obj, int *val) { long v; int res = SWIG_AsVal_long (obj, &v); if (SWIG_IsOK(res)) { if ((v < INT_MIN || v > INT_MAX)) { return SWIG_OverflowError; } else { if (val) *val = (int)(v); } } return res; } #define SWIG_From_double PyFloat_FromDouble 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); } #ifdef __cplusplus extern "C" { #endif SWIGINTERN PyObject *_wrap_Color_t_r_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; Color_t *arg1 = (Color_t *) 0 ; unsigned char arg2 ; void *argp1 = 0 ; int res1 = 0 ; unsigned char val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:Color_t_r_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Color_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Color_t_r_set" "', argument " "1"" of type '" "Color_t *""'"); } arg1 = (Color_t *)(argp1); ecode2 = SWIG_AsVal_unsigned_SS_char(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Color_t_r_set" "', argument " "2"" of type '" "unsigned char""'"); } arg2 = (unsigned char)(val2); if (arg1) (arg1)->r = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_Color_t_r_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; Color_t *arg1 = (Color_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; unsigned char result; if (!PyArg_ParseTuple(args,(char *)"O:Color_t_r_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Color_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Color_t_r_get" "', argument " "1"" of type '" "Color_t *""'"); } arg1 = (Color_t *)(argp1); result = (unsigned char) ((arg1)->r); resultobj = SWIG_From_unsigned_SS_char((unsigned char)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_Color_t_g_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; Color_t *arg1 = (Color_t *) 0 ; unsigned char arg2 ; void *argp1 = 0 ; int res1 = 0 ; unsigned char val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:Color_t_g_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Color_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Color_t_g_set" "', argument " "1"" of type '" "Color_t *""'"); } arg1 = (Color_t *)(argp1); ecode2 = SWIG_AsVal_unsigned_SS_char(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Color_t_g_set" "', argument " "2"" of type '" "unsigned char""'"); } arg2 = (unsigned char)(val2); if (arg1) (arg1)->g = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_Color_t_g_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; Color_t *arg1 = (Color_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; unsigned char result; if (!PyArg_ParseTuple(args,(char *)"O:Color_t_g_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Color_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Color_t_g_get" "', argument " "1"" of type '" "Color_t *""'"); } arg1 = (Color_t *)(argp1); result = (unsigned char) ((arg1)->g); resultobj = SWIG_From_unsigned_SS_char((unsigned char)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_Color_t_b_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; Color_t *arg1 = (Color_t *) 0 ; unsigned char arg2 ; void *argp1 = 0 ; int res1 = 0 ; unsigned char val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:Color_t_b_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Color_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Color_t_b_set" "', argument " "1"" of type '" "Color_t *""'"); } arg1 = (Color_t *)(argp1); ecode2 = SWIG_AsVal_unsigned_SS_char(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Color_t_b_set" "', argument " "2"" of type '" "unsigned char""'"); } arg2 = (unsigned char)(val2); if (arg1) (arg1)->b = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_Color_t_b_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; Color_t *arg1 = (Color_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; unsigned char result; if (!PyArg_ParseTuple(args,(char *)"O:Color_t_b_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Color_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Color_t_b_get" "', argument " "1"" of type '" "Color_t *""'"); } arg1 = (Color_t *)(argp1); result = (unsigned char) ((arg1)->b); resultobj = SWIG_From_unsigned_SS_char((unsigned char)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_new_Color_t(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; Color_t *result = 0 ; if (!PyArg_ParseTuple(args,(char *)":new_Color_t")) SWIG_fail; result = (Color_t *)calloc(1, sizeof(Color_t)); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Color_t, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_Color_t(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; Color_t *arg1 = (Color_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:delete_Color_t",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Color_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_Color_t" "', argument " "1"" of type '" "Color_t *""'"); } arg1 = (Color_t *)(argp1); free((char *) arg1); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *Color_t_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_Color_t, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_wrap_init(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; int arg1 ; int val1 ; int ecode1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:init",&obj0)) SWIG_fail; ecode1 = SWIG_AsVal_int(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "init" "', argument " "1"" of type '" "int""'"); } arg1 = (int)(val1); init(arg1); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } 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_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; } SWIGINTERN PyObject *_wrap_Wheel(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; uint8_t arg1 ; unsigned char val1 ; int ecode1 = 0 ; PyObject * obj0 = 0 ; Color_t result; if (!PyArg_ParseTuple(args,(char *)"O:Wheel",&obj0)) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_char(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "Wheel" "', argument " "1"" of type '" "uint8_t""'"); } arg1 = (uint8_t)(val1); result = Wheel(arg1); resultobj = SWIG_NewPointerObj((Color_t *)memcpy((Color_t *)malloc(sizeof(Color_t)),&result,sizeof(Color_t)), SWIGTYPE_p_Color_t, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_colorWipe(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; Color_t arg1 ; uint8_t arg2 ; void *argp1 ; int res1 = 0 ; unsigned char val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:colorWipe",&obj0,&obj1)) SWIG_fail; { res1 = SWIG_ConvertPtr(obj0, &argp1, SWIGTYPE_p_Color_t, 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "colorWipe" "', argument " "1"" of type '" "Color_t""'"); } if (!argp1) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "colorWipe" "', argument " "1"" of type '" "Color_t""'"); } else { arg1 = *((Color_t *)(argp1)); } } ecode2 = SWIG_AsVal_unsigned_SS_char(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "colorWipe" "', argument " "2"" of type '" "uint8_t""'"); } arg2 = (uint8_t)(val2); colorWipe(arg1,arg2); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_rainbow(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; uint8_t arg1 ; unsigned char val1 ; int ecode1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:rainbow",&obj0)) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_char(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "rainbow" "', argument " "1"" of type '" "uint8_t""'"); } arg1 = (uint8_t)(val1); rainbow(arg1); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_rainbowCycle(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; uint8_t arg1 ; unsigned char val1 ; int ecode1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:rainbowCycle",&obj0)) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_char(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "rainbowCycle" "', argument " "1"" of type '" "uint8_t""'"); } arg1 = (uint8_t)(val1); rainbowCycle(arg1); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_theaterChase(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; Color_t arg1 ; uint8_t arg2 ; void *argp1 ; int res1 = 0 ; unsigned char val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:theaterChase",&obj0,&obj1)) SWIG_fail; { res1 = SWIG_ConvertPtr(obj0, &argp1, SWIGTYPE_p_Color_t, 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "theaterChase" "', argument " "1"" of type '" "Color_t""'"); } if (!argp1) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "theaterChase" "', argument " "1"" of type '" "Color_t""'"); } else { arg1 = *((Color_t *)(argp1)); } } ecode2 = SWIG_AsVal_unsigned_SS_char(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "theaterChase" "', argument " "2"" of type '" "uint8_t""'"); } arg2 = (uint8_t)(val2); theaterChase(arg1,arg2); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_theaterChaseRainbow(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; uint8_t arg1 ; unsigned char val1 ; int ecode1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:theaterChaseRainbow",&obj0)) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_char(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "theaterChaseRainbow" "', argument " "1"" of type '" "uint8_t""'"); } arg1 = (uint8_t)(val1); theaterChaseRainbow(arg1); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_setBrightness(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; double arg1 ; double val1 ; int ecode1 = 0 ; PyObject * obj0 = 0 ; unsigned char result; if (!PyArg_ParseTuple(args,(char *)"O:setBrightness",&obj0)) SWIG_fail; ecode1 = SWIG_AsVal_double(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "setBrightness" "', argument " "1"" of type '" "double""'"); } arg1 = (double)(val1); result = (unsigned char)setBrightness(arg1); resultobj = SWIG_From_unsigned_SS_char((unsigned char)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_getBrightness(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; double result; if (!PyArg_ParseTuple(args,(char *)":getBrightness")) SWIG_fail; result = (double)getBrightness(); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_RGB2Color(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; unsigned char arg1 ; unsigned char arg2 ; unsigned char 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 ; Color_t result; if (!PyArg_ParseTuple(args,(char *)"OOO:RGB2Color",&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 '" "RGB2Color" "', argument " "1"" of type '" "unsigned char""'"); } arg1 = (unsigned char)(val1); ecode2 = SWIG_AsVal_unsigned_SS_char(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "RGB2Color" "', argument " "2"" of type '" "unsigned char""'"); } arg2 = (unsigned char)(val2); ecode3 = SWIG_AsVal_unsigned_SS_char(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "RGB2Color" "', argument " "3"" of type '" "unsigned char""'"); } arg3 = (unsigned char)(val3); result = RGB2Color(arg1,arg2,arg3); resultobj = SWIG_NewPointerObj((Color_t *)memcpy((Color_t *)malloc(sizeof(Color_t)),&result,sizeof(Color_t)), SWIGTYPE_p_Color_t, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_Color(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; unsigned char arg1 ; unsigned char arg2 ; unsigned char 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 ; Color_t result; if (!PyArg_ParseTuple(args,(char *)"OOO:Color",&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 '" "Color" "', argument " "1"" of type '" "unsigned char""'"); } arg1 = (unsigned char)(val1); ecode2 = SWIG_AsVal_unsigned_SS_char(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Color" "', argument " "2"" of type '" "unsigned char""'"); } arg2 = (unsigned char)(val2); ecode3 = SWIG_AsVal_unsigned_SS_char(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "Color" "', argument " "3"" of type '" "unsigned char""'"); } arg3 = (unsigned char)(val3); result = Color(arg1,arg2,arg3); resultobj = SWIG_NewPointerObj((Color_t *)memcpy((Color_t *)malloc(sizeof(Color_t)),&result,sizeof(Color_t)), SWIGTYPE_p_Color_t, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_setPixelColor(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; unsigned int arg1 ; unsigned char arg2 ; unsigned char arg3 ; unsigned char arg4 ; unsigned int 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 ; unsigned char result; if (!PyArg_ParseTuple(args,(char *)"OOOO:setPixelColor",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_int(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "setPixelColor" "', argument " "1"" of type '" "unsigned int""'"); } arg1 = (unsigned int)(val1); ecode2 = SWIG_AsVal_unsigned_SS_char(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "setPixelColor" "', argument " "2"" of type '" "unsigned char""'"); } arg2 = (unsigned char)(val2); ecode3 = SWIG_AsVal_unsigned_SS_char(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "setPixelColor" "', argument " "3"" of type '" "unsigned char""'"); } arg3 = (unsigned char)(val3); ecode4 = SWIG_AsVal_unsigned_SS_char(obj3, &val4); if (!SWIG_IsOK(ecode4)) { SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "setPixelColor" "', argument " "4"" of type '" "unsigned char""'"); } arg4 = (unsigned char)(val4); result = (unsigned char)setPixelColor(arg1,arg2,arg3,arg4); resultobj = SWIG_From_unsigned_SS_char((unsigned char)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_setPixelColorT(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; unsigned int arg1 ; Color_t arg2 ; unsigned int val1 ; int ecode1 = 0 ; void *argp2 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; unsigned char result; if (!PyArg_ParseTuple(args,(char *)"OO:setPixelColorT",&obj0,&obj1)) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_int(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "setPixelColorT" "', argument " "1"" of type '" "unsigned int""'"); } arg1 = (unsigned int)(val1); { res2 = SWIG_ConvertPtr(obj1, &argp2, SWIGTYPE_p_Color_t, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "setPixelColorT" "', argument " "2"" of type '" "Color_t""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "setPixelColorT" "', argument " "2"" of type '" "Color_t""'"); } else { arg2 = *((Color_t *)(argp2)); } } result = (unsigned char)setPixelColorT(arg1,arg2); resultobj = SWIG_From_unsigned_SS_char((unsigned char)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_getPixelColor(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; unsigned int arg1 ; unsigned int val1 ; int ecode1 = 0 ; PyObject * obj0 = 0 ; Color_t result; if (!PyArg_ParseTuple(args,(char *)"O:getPixelColor",&obj0)) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_int(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "getPixelColor" "', argument " "1"" of type '" "unsigned int""'"); } arg1 = (unsigned int)(val1); result = getPixelColor(arg1); resultobj = SWIG_NewPointerObj((Color_t *)memcpy((Color_t *)malloc(sizeof(Color_t)),&result,sizeof(Color_t)), SWIGTYPE_p_Color_t, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_numPixels(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; unsigned int result; if (!PyArg_ParseTuple(args,(char *)":numPixels")) SWIG_fail; result = (unsigned int)numPixels(); resultobj = SWIG_From_unsigned_SS_int((unsigned int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_getPixels(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; Color_t *result = 0 ; if (!PyArg_ParseTuple(args,(char *)":getPixels")) SWIG_fail; result = (Color_t *)getPixels(); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Color_t, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_setPWMBit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; unsigned int arg1 ; unsigned char arg2 ; unsigned int val1 ; int ecode1 = 0 ; unsigned char val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:setPWMBit",&obj0,&obj1)) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_int(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "setPWMBit" "', argument " "1"" of type '" "unsigned int""'"); } arg1 = (unsigned int)(val1); ecode2 = SWIG_AsVal_unsigned_SS_char(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "setPWMBit" "', argument " "2"" of type '" "unsigned char""'"); } arg2 = (unsigned char)(val2); setPWMBit(arg1,arg2); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_getPWMBit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; unsigned int arg1 ; unsigned int val1 ; int ecode1 = 0 ; PyObject * obj0 = 0 ; unsigned char result; if (!PyArg_ParseTuple(args,(char *)"O:getPWMBit",&obj0)) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_int(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "getPWMBit" "', argument " "1"" of type '" "unsigned int""'"); } arg1 = (unsigned int)(val1); result = (unsigned char)getPWMBit(arg1); resultobj = SWIG_From_unsigned_SS_char((unsigned char)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_dumpLEDBuffer(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; if (!PyArg_ParseTuple(args,(char *)":dumpLEDBuffer")) SWIG_fail; dumpLEDBuffer(); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_dumpPWMBuffer(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; if (!PyArg_ParseTuple(args,(char *)":dumpPWMBuffer")) SWIG_fail; dumpPWMBuffer(); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_dumpPWMStatus(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; if (!PyArg_ParseTuple(args,(char *)":dumpPWMStatus")) SWIG_fail; dumpPWMStatus(); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_dumpPWMControl(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; unsigned int arg1 ; unsigned int val1 ; int ecode1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:dumpPWMControl",&obj0)) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_int(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "dumpPWMControl" "', argument " "1"" of type '" "unsigned int""'"); } arg1 = (unsigned int)(val1); dumpPWMControl(arg1); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_dumpPWMDMAC(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; if (!PyArg_ParseTuple(args,(char *)":dumpPWMDMAC")) SWIG_fail; dumpPWMDMAC(); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_dumpPWM(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; if (!PyArg_ParseTuple(args,(char *)":dumpPWM")) SWIG_fail; dumpPWM(); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_dumpDMARegs(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; if (!PyArg_ParseTuple(args,(char *)":dumpDMARegs")) SWIG_fail; dumpDMARegs(); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_dumpControlBlock(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; dma_cb_t *arg1 = (dma_cb_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:dumpControlBlock",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_dma_cb_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "dumpControlBlock" "', argument " "1"" of type '" "dma_cb_t *""'"); } arg1 = (dma_cb_t *)(argp1); dumpControlBlock(arg1); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_dumpTransferInformation(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; unsigned int arg1 ; unsigned int val1 ; int ecode1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:dumpTransferInformation",&obj0)) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_int(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "dumpTransferInformation" "', argument " "1"" of type '" "unsigned int""'"); } arg1 = (unsigned int)(val1); dumpTransferInformation(arg1); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_dumpDMA(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; if (!PyArg_ParseTuple(args,(char *)":dumpDMA")) SWIG_fail; dumpDMA(); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_terminate(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; int arg1 ; int val1 ; int ecode1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:terminate",&obj0)) SWIG_fail; ecode1 = SWIG_AsVal_int(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "terminate" "', argument " "1"" of type '" "int""'"); } arg1 = (int)(val1); terminate(arg1); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } static PyMethodDef SwigMethods[] = { { (char *)"SWIG_PyInstanceMethod_New", (PyCFunction)SWIG_PyInstanceMethod_New, METH_O, NULL}, { (char *)"Color_t_r_set", _wrap_Color_t_r_set, METH_VARARGS, NULL}, { (char *)"Color_t_r_get", _wrap_Color_t_r_get, METH_VARARGS, NULL}, { (char *)"Color_t_g_set", _wrap_Color_t_g_set, METH_VARARGS, NULL}, { (char *)"Color_t_g_get", _wrap_Color_t_g_get, METH_VARARGS, NULL}, { (char *)"Color_t_b_set", _wrap_Color_t_b_set, METH_VARARGS, NULL}, { (char *)"Color_t_b_get", _wrap_Color_t_b_get, METH_VARARGS, NULL}, { (char *)"new_Color_t", _wrap_new_Color_t, METH_VARARGS, NULL}, { (char *)"delete_Color_t", _wrap_delete_Color_t, METH_VARARGS, NULL}, { (char *)"Color_t_swigregister", Color_t_swigregister, METH_VARARGS, NULL}, { (char *)"init", _wrap_init, METH_VARARGS, NULL}, { (char *)"clear", _wrap_clear, METH_VARARGS, NULL}, { (char *)"show", _wrap_show, METH_VARARGS, NULL}, { (char *)"Wheel", _wrap_Wheel, METH_VARARGS, NULL}, { (char *)"colorWipe", _wrap_colorWipe, METH_VARARGS, NULL}, { (char *)"rainbow", _wrap_rainbow, METH_VARARGS, NULL}, { (char *)"rainbowCycle", _wrap_rainbowCycle, METH_VARARGS, NULL}, { (char *)"theaterChase", _wrap_theaterChase, METH_VARARGS, NULL}, { (char *)"theaterChaseRainbow", _wrap_theaterChaseRainbow, METH_VARARGS, NULL}, { (char *)"setBrightness", _wrap_setBrightness, METH_VARARGS, NULL}, { (char *)"getBrightness", _wrap_getBrightness, METH_VARARGS, NULL}, { (char *)"RGB2Color", _wrap_RGB2Color, METH_VARARGS, NULL}, { (char *)"Color", _wrap_Color, METH_VARARGS, NULL}, { (char *)"setPixelColor", _wrap_setPixelColor, METH_VARARGS, NULL}, { (char *)"setPixelColorT", _wrap_setPixelColorT, METH_VARARGS, NULL}, { (char *)"getPixelColor", _wrap_getPixelColor, METH_VARARGS, NULL}, { (char *)"numPixels", _wrap_numPixels, METH_VARARGS, NULL}, { (char *)"getPixels", _wrap_getPixels, METH_VARARGS, NULL}, { (char *)"setPWMBit", _wrap_setPWMBit, METH_VARARGS, NULL}, { (char *)"getPWMBit", _wrap_getPWMBit, METH_VARARGS, NULL}, { (char *)"dumpLEDBuffer", _wrap_dumpLEDBuffer, METH_VARARGS, NULL}, { (char *)"dumpPWMBuffer", _wrap_dumpPWMBuffer, METH_VARARGS, NULL}, { (char *)"dumpPWMStatus", _wrap_dumpPWMStatus, METH_VARARGS, NULL}, { (char *)"dumpPWMControl", _wrap_dumpPWMControl, METH_VARARGS, NULL}, { (char *)"dumpPWMDMAC", _wrap_dumpPWMDMAC, METH_VARARGS, NULL}, { (char *)"dumpPWM", _wrap_dumpPWM, METH_VARARGS, NULL}, { (char *)"dumpDMARegs", _wrap_dumpDMARegs, METH_VARARGS, NULL}, { (char *)"dumpControlBlock", _wrap_dumpControlBlock, METH_VARARGS, NULL}, { (char *)"dumpTransferInformation", _wrap_dumpTransferInformation, METH_VARARGS, NULL}, { (char *)"dumpDMA", _wrap_dumpDMA, METH_VARARGS, NULL}, { (char *)"terminate", _wrap_terminate, METH_VARARGS, NULL}, { NULL, NULL, 0, NULL } }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ static swig_type_info _swigt__p_Color_t = {"_p_Color_t", "Color_t *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_dma_cb_t = {"_p_dma_cb_t", "dma_cb_t *", 0, 0, (void*)0, 0}; static swig_type_info *swig_type_initial[] = { &_swigt__p_Color_t, &_swigt__p_char, &_swigt__p_dma_cb_t, }; static swig_cast_info _swigc__p_Color_t[] = { {&_swigt__p_Color_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_dma_cb_t[] = { {&_swigt__p_dma_cb_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { _swigc__p_Color_t, _swigc__p_char, _swigc__p_dma_cb_t, }; /* -------- 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 staticly 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; clientdata = clientdata; /* 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 interpeters 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_SetString(PyExc_NameError,"Unknown C global variable"); } 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_SetString(PyExc_NameError,"Unknown C global variable"); } 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); 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 } ./library/legacy/ws2812/README.txt0000664000175000017500000000000014223621661017506 0ustar jawn-smithjawn-smith./library/legacy/ws2812/setup.py0000775000175000017500000000150114223621661017534 0ustar jawn-smithjawn-smith#!/usr/bin/env python from setuptools import setup, find_packages, Extension cpu = open('/proc/cpuinfo','r').read() define = [] if 'ARMv7' in cpu: define = [('RPI2',''),('PERI_BASE','0x3F000000')] _ws2812 = Extension( '_ws2812', define_macros = define, library_dirs= [ 'lib/' ], include_dirs= [ 'lib/' ], sources = [ 'lib/ws2812-RPi.c', 'ws2812-RPi_wrap.c' ] ) setup( name = 'ws2812', version = '1.1.0', author = 'Philip Howard', author_email= 'phil@pimoroni.com', url = 'https://github.com/pimoroni/ws2812-RPi/', description = """A python interface to ws2812 RPi""", long_description=open('README').read(), ext_modules = [ _ws2812 ], py_modules = [ 'ws2812' ], install_requires = [], headers = [ 'lib/ws2812-RPi.h' ] ) ./library/legacy/ws2812/README.md0000664000175000017500000000263514223621661017307 0ustar jawn-smithjawn-smithws2812 Python Module ==================== Usage ----- Install with: sudo ./setup.py install Then: import ws2812 numPixels = 64 ws2812.init(64) idx = 0 r = 255 g = 0 b = 255 ws2812.setPixelColor(idx, r, g, b) ws2812.show() Reference --------- * init(numPixels) - Initialise the hardware and set the number of pixels to update * clear() - Clear the LED buffer * setPixelColor(index, r, g, b) - Change the colour of a single LED * setPixelColor(index, color) - Same as above, using color object * show() - Update the LEDs with current buffer * Color(r, g, b) - Create an instance of color, for use with setPixelColor, theaterChase, etc. * Wheel(0 - 255) - From Adafruit ws2812 demos, gets an RGB colour * rainbow(wait) - Animates a rainbow across pixels, delay of "wait" * rainbowCycle(wait) - Same as above, with a slightly different animation * theaterChase(color, wait) - Animate a colour across pixels * terminate(0) - Should ideally be called upon exiting to clean up hardware Changes ------- Please do not modify ws2812-RPi_wrap.c or ws2812.py directly. You should change only the bindings file: ws2812-RPi.i Changes to this file will let you use SWIG to auto-generate the correct bindings: swig2.0 -python ws2812-RPi.i If you wish to add any Python methods for a specific product or application, then it's recommended that you create a separate module ( like UnicornHat )../library/legacy/ws2812/lib/0000775000175000017500000000000014223621661016570 5ustar jawn-smithjawn-smith./library/legacy/ws2812/lib/ws2812-RPi.h0000664000175000017500000005043414223621661020405 0ustar jawn-smithjawn-smith// Set tabs to 4 spaces. // ================================================================================================= // // WS2812 NeoPixel driver // Based on code by Richard G. Hirst and others // Adapted for the WS2812 by 626Pilot, April/May 2014 // Huge ASCII art section labels are from http://patorjk.com/software/taag/ // // License: GPL // // You are using this at your OWN RISK. I believe this software is reasonably safe to use (aside // from the intrinsic risk to those who are photosensitive - see below), although I can't be certain // that it won't trash your hardware or cause property damage. // // Speaking of risk, WS2812 pixels are bright enough to cause eye pain and (for all I know) possibly // retina damage when run at full strength. It's a good idea to set the brightness at 0.2 or so for // direct viewing (whether you're looking directly at the pixels or not), or to put some diffuse // material between you and the LEDs. // // PHOTOSENSITIVITY WARNING: // Patterns of light and darkness (stationary or moving), flashing lights, patterns and backgrounds // on screens, and the like, may cause epilleptic seizures in some people. This is a danger EVEN IF // THE PERSON (WHICH MAY BE *YOU*) HAS NEVER KNOWINGLY HAD A PHOTOSENSITIVE EPISODE BEFORE. It's up // to you to learn the warning signs, but symptoms may include dizziness, nausea, vision changes, // convlusions, disorientation, involuntary movements, and eye twitching. (This list is not // necessarily exhaustive.) // // NEOPIXEL BEST PRACTICES: https://learn.adafruit.com/adafruit-neopixel-uberguide/best-practices // // Connections: // Positive to Raspberry Pi's 3.3v // Negative to Raspberry Pi's ground // Data to GPIO18 (Pin 12) (through a resistor, which you should know from the Best // Practices guide!) // // GitHub (source, support, etc.): https://github.com/626Pilot/RaspberryPi-NeoPixel-WS2812 // Buy WS2812-based stuff from: http://adafruit.com // Compile with: gcc ws2812-RPi.c -o ws2812-RPi // Test with: sudo ./ws2812-RPi // (it needs to be root so it can map the peripherals' registers) // // ================================================================================================= // This is for the WS2812 LEDs. It won't work with the older WS2811s, although it could be modified // for that without too much trouble. Preliminary driver used Frank Buss' servo driver, but I moved // to Richard Hirst's memory mapping/access model because his code already works with DMA, and has // what I think is a slightly cleaner way of accessing the registers: register[name] rather than // *(register + name). // At the time of writing, there's a lot of confusing "PWM DMA" code revolving around simulating // an FM signal. Usually this is done without properly initializing certain registers, which is // OK for their purpose, but I needed to be able to transfer actual coherent data and have it wind // up in a proper state once it was transferred. This has proven to be a somewhat painful task. // The PWM controller likes to ignore the RPTL1 bit when the data is in a regular, repeating // pattern. I'M NOT MAKING IT UP! It really does that. It's bizarre. There are lots of other // strange irregularities as well, which had to be figured out through trial and error. It doesn't // help that the BCM2835 ARM Peripherals manual contains outright errors and omissions! // Many examples of this kind of code have magic numbers in them. If you don't know, a magic number // is one that either lacks an obvious structure (e.g. 0x2020C000) or purpose. Please don't use // that stuff in any code you release! All magic numbers found in reference code have been changed // to DEFINEs. That way, instead of seeing some inscrutable number, you see (e.g.) PWM_CTL. // References - BCM2835 ARM Peripherals: // http://www.raspberrypi.org/wp-content/uploads/2012/02/BCM2835-ARM-Peripherals.pdf // // Raspberry Pi low-level peripherals: // http://elinux.org/RPi_Low-level_peripherals // // Richard Hirst's nice, clean code: // https://github.com/richardghirst/PiBits/blob/master/PiFmDma/PiFmDma.c // // PWM clock register: // http://www.raspberrypi.org/forums/viewtopic.php?t=8467&p=124620 // // Simple (because it's in assembly) PWM+DMA setup: // https://github.com/mikedurso/rpi-projects/blob/master/asm-nyancat/rpi-nyancat.s // // Adafruit's NeoPixel driver: // https://github.com/adafruit/Adafruit_NeoPixel/blob/master/Adafruit_NeoPixel.cpp #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef PERI_BASE // 0x3F000000 Pi 2 // 0x20000000 Pi 1 #define PERI_BASE 0x20000000 #warning Defaulting PERI_BASE to 0x20000000 #endif // Base addresses for GPIO, PWM, PWM clock, and DMA controllers (physical, not bus!) // These will be "memory mapped" into virtual RAM so that they can be written and read directly. #define DMA_BASE PERI_BASE + 0x7000 #define DMA_LEN 0x24 #define PWM_BASE PERI_BASE + 0x20C000 #define PWM_LEN 0x28 #define CLK_BASE PERI_BASE + 0x101000 #define CLK_LEN 0xA8 #define GPIO_BASE PERI_BASE + 0x200000 #define GPIO_LEN 0xB4 // GPIO // ------------------------------------------------------------------------------------------------- #define GPFSEL1 PERI_BASE + 0x200004 // Pins 10-19 #define GPFSEL2 PERI_BASE + 0x200008 // Pins 20-29 #define GPFSEL3 PERI_BASE + 0x20000C // Pins 30-39 #define GPFSEL4 PERI_BASE + 0x200010 // Pins 40-49 #define GPFSEL5 PERI_BASE + 0x200014 // Pins 50-53 #define GPSET0 PERI_BASE + 0x20001C // Set (turn on) pin #define GPCLR0 PERI_BASE + 0x200028 // Clear (turn off) pin #define GPPUD PERI_BASE + 0x200094 // Internal pullup/pulldown resistor control #define GPPUDCLK0 PERI_BASE + 0x200098 // PUD clock for pins 0-31 #define GPPUDCLK1 PERI_BASE + 0x20009C // PUD clock for pins 32-53 // Memory offsets for the PWM clock register, which is undocumented! Please fix that, Broadcom! // ------------------------------------------------------------------------------------------------- #define PWM_CLK_CNTL 40 // Control (on/off) #define PWM_CLK_DIV 41 // Divisor (bits 11:0 are *quantized* floating part, 31:12 integer part) // PWM Register Addresses (page 141) // These are divided by 4 because the register offsets in the guide are in bytes (8 bits) but // the pointers we use in this program are in words (32 bits). Buss' original defines are in // word offsets, e.g. PWM_RNG1 was 4 and PWM_DAT1 was 5. This is functionally the same, but it // matches the numbers supplied in the guide. // ------------------------------------------------------------------------------------------------- #define PWM_CTL 0x00 // Control Register #define PWM_STA (0x04 / 4) // Status Register #define PWM_DMAC (0x08 / 4) // DMA Control Register #define PWM_RNG1 (0x10 / 4) // Channel 1 Range #define PWM_DAT1 (0x14 / 4) // Channel 1 Data #define PWM_FIF1 (0x18 / 4) // FIFO (for both channels - bytes are interleaved if both active) #define PWM_RNG2 (0x20 / 4) // Channel 2 Range #define PWM_DAT2 (0x24 / 4) // Channel 2 Data // PWM_CTL register bit offsets // Note: Don't use MSEN1/2 for this purpose. It will screw things up. // ------------------------------------------------------------------------------------------------- #define PWM_CTL_MSEN2 15 // Channel 2 - 0: Use PWM algorithm. 1: Use M/S (serial) algorithm. #define PWM_CTL_USEF2 13 // Channel 2 - 0: Use PWM_DAT2. 1: Use FIFO. #define PWM_CTL_POLA2 12 // Channel 2 - Invert output polarity (if set, 0=high and 1=low) #define PWM_CTL_SBIT2 11 // Channel 2 - Silence bit (default line state when not transmitting) #define PWM_CTL_RPTL2 10 // Channel 2 - Repeat last data in FIFO #define PWM_CTL_MODE2 9 // Channel 2 - Mode. 0=PWM, 1=Serializer #define PWM_CTL_PWEN2 8 // Channel 2 - Enable PWM #define PWM_CTL_CLRF1 6 // Clear FIFO #define PWM_CTL_MSEN1 7 // Channel 1 - 0: Use PWM algorithm. 1: Use M/S (serial) algorithm. #define PWM_CTL_USEF1 5 // Channel 1 - 0: Use PWM_DAT1. 1: Use FIFO. #define PWM_CTL_POLA1 4 // Channel 1 - Invert output polarity (if set, 0=high and 1=low) #define PWM_CTL_SBIT1 3 // Channel 1 - Silence bit (default line state when not transmitting) #define PWM_CTL_RPTL1 2 // Channel 1 - Repeat last data in FIFO #define PWM_CTL_MODE1 1 // Channel 1 - Mode. 0=PWM, 1=Serializer #define PWM_CTL_PWEN1 0 // Channel 1 - Enable PWM // PWM_STA register bit offsets // ------------------------------------------------------------------------------------------------- #define PWM_STA_STA4 12 // Channel 4 State #define PWM_STA_STA3 11 // Channel 3 State #define PWM_STA_STA2 10 // Channel 2 State #define PWM_STA_STA1 9 // Channel 1 State #define PWM_STA_BERR 8 // Bus Error #define PWM_STA_GAPO4 7 // Gap Occurred on Channel 4 #define PWM_STA_GAPO3 6 // Gap Occurred on Channel 3 #define PWM_STA_GAPO2 5 // Gap Occurred on Channel 2 #define PWM_STA_GAPO1 4 // Gap Occurred on Channel 1 #define PWM_STA_RERR1 3 // FIFO Read Error #define PWM_STA_WERR1 2 // FIFO Write Error #define PWM_STA_EMPT1 1 // FIFO Empty #define PWM_STA_FULL1 0 // FIFO Full // PWM_DMAC bit offsets // ------------------------------------------------------------------------------------------------- #define PWM_DMAC_ENAB 31 // 0: DMA Disabled. 1: DMA Enabled. #define PWM_DMAC_PANIC 8 // Bits 15:8. Threshold for PANIC signal. Default 7. #define PWM_DMAC_DREQ 0 // Bits 7:0. Threshold for DREQ signal. Default 7. // PWM_RNG1, PWM_RNG2 // -------------------------------------------------------------------------------------------------- // Defines the transmission range. In PWM mode, evenly spaced pulses are sent within a period // of length defined in these registers. In serial mode, serialized data is sent within the // same period. The value is normally 32. If less, data will be truncated. If more, data will // be padded with zeros. // DAT1, DAT2 // -------------------------------------------------------------------------------------------------- // NOTE: These registers are not useful for our purposes - we will use the FIFO instead! // Stores 32 bits of data to be sent when USEF1/USEF2 is 0. In PWM mode, defines how many // pulses will be sent within the period specified in PWM_RNG1/PWM_RNG2. In serializer mode, // defines a 32-bit word to be transmitted. // FIF1 // -------------------------------------------------------------------------------------------------- // 32-bit-wide register used to "stuff" the FIFO, which has 16 32-bit words. (So, if you write // it 16 times, it will fill the FIFO.) // See also: PWM_STA_EMPT1 (FIFO empty) // PWM_STA_FULL1 (FIFO full) // PWM_CTL_CLRF1 (Clear FIFO) // DMA // -------------------------------------------------------------------------------------------------- // DMA registers (divided by four to convert form word to byte offsets, as with the PWM registers) #define DMA_CS (0x00 / 4) // Control & Status register #define DMA_CONBLK_AD (0x04 / 4) // Address of Control Block (must be 256-BYTE ALIGNED!!!) #define DMA_TI (0x08 / 4) // Transfer Information (populated from CB) #define DMA_SOURCE_AD (0x0C / 4) // Source address, populated from CB. Physical address. #define DMA_DEST_AD (0x10 / 4) // Destination address, populated from CB. Bus address. #define DMA_TXFR_LEN (0x14 / 4) // Transfer length, populated from CB #define DMA_STRIDE (0x18 / 4) // Stride, populated from CB #define DMA_NEXTCONBK (0x1C / 4) // Next control block address, populated from CB #define DMA_DEBUG (0x20 / 4) // Debug settings // DMA Control & Status register bit offsets #define DMA_CS_RESET 31 // Reset the controller for this channel #define DMA_CS_ABORT 30 // Set to abort transfer #define DMA_CS_DISDEBUG 29 // Disable debug pause signal #define DMA_CS_WAIT_FOR 28 // Wait for outstanding writes #define DMA_CS_PANIC_PRI 20 // Panic priority (bits 23:20), default 7 #define DMA_CS_PRIORITY 16 // AXI priority level (bits 19:16), default 7 #define DMA_CS_ERROR 8 // Set when there's been an error #define DMA_CS_WAITING_FOR 6 // Set when the channel's waiting for a write to be accepted #define DMA_CS_DREQ_STOPS_DMA 5 // Set when the DMA is paused because DREQ is inactive #define DMA_CS_PAUSED 4 // Set when the DMA is paused (active bit cleared, etc.) #define DMA_CS_DREQ 3 // Set when DREQ line is high #define DMA_CS_INT 2 // If INTEN is set, this will be set on CB transfer end #define DMA_CS_END 1 // Set when the current control block is finished #define DMA_CS_ACTIVE 0 // Enable DMA (CB_ADDR must not be 0) // Default CS word #define DMA_CS_CONFIGWORD (8 << DMA_CS_PANIC_PRI) | \ (8 << DMA_CS_PRIORITY) | \ (1 << DMA_CS_WAIT_FOR) // DREQ lines (page 61, most DREQs omitted) #define DMA_DREQ_ALWAYS 0 #define DMA_DREQ_PCM_TX 2 #define DMA_DREQ_PCM_RX 3 #define DMA_DREQ_PWM 5 #define DMA_DREQ_SPI_TX 6 #define DMA_DREQ_SPI_RX 7 #define DMA_DREQ_BSC_TX 8 #define DMA_DREQ_BSC_RX 9 // DMA Transfer Information register bit offsets // We don't write DMA_TI directly. It's populated from the TI field in a control block. #define DMA_TI_NO_WIDE_BURSTS 26 // Don't do wide writes in 2-beat bursts #define DMA_TI_WAITS 21 // Wait this many cycles after end of each read/write #define DMA_TI_PERMAP 16 // Peripheral # whose ready signal controls xfer rate (pwm=5) #define DMA_TI_BURST_LENGTH 12 // Length of burst in words (bits 15:12) #define DMA_TI_SRC_IGNORE 11 // Don't perform source reads (for fast cache fill) #define DMA_TI_SRC_DREQ 10 // Peripheral in PERMAP gates source reads #define DMA_TI_SRC_WIDTH 9 // Source transfer width - 0=32 bits, 1=128 bits #define DMA_TI_SRC_INC 8 // Source address += SRC_WITH after each read #define DMA_TI_DEST_IGNORE 7 // Don't perform destination writes #define DMA_TI_DEST_DREQ 6 // Peripheral in PERMAP gates destination writes #define DMA_TI_DEST_WIDTH 5 // Destination transfer width - 0=32 bits, 1=128 bits #define DMA_TI_DEST_INC 4 // Dest address += DEST_WIDTH after each read #define DMA_TI_WAIT_RESP 3 // Wait for write response #define DMA_TI_TDMODE 1 // 2D striding mode #define DMA_TI_INTEN 0 // Interrupt enable // Default TI word #define DMA_TI_CONFIGWORD (1 << DMA_TI_NO_WIDE_BURSTS) | \ (1 << DMA_TI_SRC_INC) | \ (1 << DMA_TI_DEST_DREQ) | \ (1 << DMA_TI_WAIT_RESP) | \ (1 << DMA_TI_INTEN) | \ (DMA_DREQ_PWM << DMA_TI_PERMAP) // DMA Debug register bit offsets #define DMA_DEBUG_LITE 28 // Whether the controller is "Lite" #define DMA_DEBUG_VERSION 25 // DMA Version (bits 27:25) #define DMA_DEBUG_DMA_STATE 16 // DMA State (bits 24:16) #define DMA_DEBUG_DMA_ID 8 // DMA controller's AXI bus ID (bits 15:8) #define DMA_DEBUG_OUTSTANDING_WRITES 4 // Outstanding writes (bits 7:4) #define DMA_DEBUG_READ_ERROR 2 // Slave read response error (clear by setting) #define DMA_DEBUG_FIFO_ERROR 1 // Operational read FIFO error (clear by setting) #define DMA_DEBUG_READ_LAST_NOT_SET 0 // AXI bus read last signal not set (clear by setting) // Control Block (CB) - this tells the DMA controller what to do. typedef struct { unsigned int info, // Transfer Information (TI) src, // Source address (physical) dst, // Destination address (bus) length, // Length in bytes (not words!) stride, // We don't care about this next, // Pointer to next control block pad[2]; // These are "reserved" (unused) } dma_cb_t; // The page map contains pointers to memory that we will allocate below. It uses two pointers // per address. This is because the software (this program) deals only in virtual addresses, // whereas the DMA controller can only access RAM via physical address. (If that's not confusing // enough, it writes to peripherals by their bus addresses.) typedef struct { uint8_t *virtaddr; uint32_t physaddr; } page_map_t; page_map_t *page_map; // This will hold the page map, which we'll allocate below static uint8_t *virtbase; // Pointer to some virtual memory that will be allocated static volatile unsigned int *pwm_reg; // PWM controller register set static volatile unsigned int *clk_reg; // PWM clock manager register set static volatile unsigned int *dma_reg; // DMA controller register set static volatile unsigned int *gpio_reg; // GPIO pin controller register set // Contains arrays of control blocks and their related samples. // One pixel needs 72 bits (24 bits for the color * 3 to represent them on the wire). // 768 words = 341.3 pixels // 1024 words = 455.1 pixels // The highest I can make this number is 1016. Any higher, and it will start copying garbage to the // PWM controller. I think it might be because of the virtual->physical memory mapping not being // contiguous, so *pointer+1016 isn't "next door" to *pointer+1017 for some weird reason. // However, that's still enough for 451.5 color instructions! If someone has more pixels than that // to control, they can figure it out. I tried Hirst's message of having one CB per word, which // seems like it might fix that, but I couldn't figure it out. #define NUM_DATA_WORDS 1016 struct control_data_s { dma_cb_t cb[1]; uint32_t sample[NUM_DATA_WORDS]; }; static struct control_data_s *ctl; #define PAGE_SIZE 4096 // Size of a RAM page to be allocated #define PAGE_SHIFT 12 // This is used for address translation #define NUM_PAGES ((sizeof(struct control_data_s) + PAGE_SIZE - 1) >> PAGE_SHIFT) #define SETBIT(word, bit) word |= 1<=0; x--) { printf("%d", (i & (1 << x)) ? 1 : 0); if(x % 16 == 0 && x > 0) { printf(" "); } else if(x % 4 == 0 && x > 0) { printf(":"); } } } // Reverse the bits in a word unsigned int reverseWord(unsigned int word) { unsigned int output = 0; unsigned char bit; int i; for(i=0; i<32; i++) { bit = word & (1 << i) ? 1 : 0; output |= word & (1 << i) ? 1 : 0; if(i<31) { output <<= 1; } } return output; } // Not sure how this is better than usleep...? /* static void udelay(int us) { struct timespec ts = { 0, us * 1000 }; nanosleep(&ts, NULL); } */ // Shutdown functions void terminate(int dummy) { // Shut down the DMA controller if(dma_reg) { CLRBIT(dma_reg[DMA_CS], DMA_CS_ACTIVE); usleep(100); SETBIT(dma_reg[DMA_CS], DMA_CS_RESET); usleep(100); } // Shut down PWM if(pwm_reg) { CLRBIT(pwm_reg[PWM_CTL], PWM_CTL_PWEN1); usleep(100); pwm_reg[PWM_CTL] = (1 << PWM_CTL_CLRF1); } // Free the allocated memory if(page_map != 0) { free(page_map); } } void fatal(char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); terminate(0); exit(1); } // Memory management // Translate from virtual address to physical unsigned int mem_virt_to_phys(void *virt) { unsigned int offset = (uint8_t *)virt - virtbase; return (page_map[offset >> PAGE_SHIFT].physaddr + (offset % PAGE_SIZE)) | 0xC0000000; } // Translate from physical address to virtual unsigned int mem_phys_to_virt(uint32_t phys) { unsigned int pg_offset = phys & (PAGE_SIZE - 1); unsigned int pg_addr = phys - pg_offset; int i; for (i = 0; i < NUM_PAGES; i++) { if (page_map[i].physaddr == pg_addr) { return ((uint32_t)virtbase + i * PAGE_SIZE + pg_offset) | 0xC0000000; } } fatal("Failed to reverse map phys addr %08x\n", phys); return 0; } // Map a peripheral's IO memory into our virtual memory, so we can read/write it directly void * map_peripheral(uint32_t base, uint32_t len) { int fd = open("/dev/mem", O_RDWR); void * vaddr; if (fd < 0) fatal("Failed to open /dev/mem: %m\n"); vaddr = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, base); if (vaddr == MAP_FAILED) fatal("Failed to map peripheral at 0x%08x: %m\n", base); close(fd); return vaddr; } // LED stuff // Set brightness unsigned char setBrightness(double b) { if(b < 0) { printf("Brightness can't be set below 0.\n"); return false; } if(b > 1) { printf("Brightness can't be set above 1.\n"); return false; } brightness = b; return true; } double getBrightness(){ return brightness; } // Zero out the PWM waveform buffer void clearPWMBuffer(void) { memset(PWMWaveform, 0, NUM_DATA_WORDS * 4); // Times four because memset deals in bytes. } void clear(void){ clearLEDBuffer(); } // Zero out the LED buffer void clearLEDBuffer(void) { int i; for(i=0; i LED_BUFFER_LENGTH - 1) { printf("Unable to set pixel %d (LED buffer is %d pixels long)\n", pixel, LED_BUFFER_LENGTH); return false; } LEDBuffer[pixel] = RGB2Color(r, g, b); return true; } // Set pixel color, by a direct Color_t unsigned char setPixelColorT(unsigned int pixel, Color_t c) { if(pixel < 0) { printf("Unable to set pixel %d (less than zero?)\n", pixel); return false; } if(pixel > LED_BUFFER_LENGTH - 1) { printf("Unable to set pixel %d (LED buffer is %d pixels long)\n", pixel, LED_BUFFER_LENGTH); return false; } LEDBuffer[pixel] = c; return true; } // Get pixel color Color_t getPixelColor(unsigned int pixel) { if(pixel < 0) { printf("Unable to get pixel %d (less than zero?)\n", pixel); return RGB2Color(0, 0, 0); } if(pixel > LED_BUFFER_LENGTH - 1) { printf("Unable to get pixel %d (LED buffer is %d pixels long)\n", pixel, LED_BUFFER_LENGTH); return RGB2Color(0, 0, 0); } return LEDBuffer[pixel]; } // Return # of pixels unsigned int numPixels(void) { return numLEDs; } // Return pointer to pixels (FIXME: dunno if this works!) Color_t* getPixels(void) { return LEDBuffer; } // Set an individual bit in the PWM output array, accounting for word boundaries // The (31 - bitIdx) is so that we write the data backwards, correcting its endianness // This means getPWMBit will return something other than what was written, so it would be nice // if the logic that calls this function would figure it out instead. (However, that's trickier) void setPWMBit(unsigned int bitPos, unsigned char bit) { // Fetch word the bit is in unsigned int wordOffset = (int)(bitPos / 32); unsigned int bitIdx = bitPos - (wordOffset * 32); // printf("bitPos=%d wordOffset=%d bitIdx=%d value=%d\n", bitPos, wordOffset, bitIdx, bit); switch(bit) { case 1: PWMWaveform[wordOffset] |= (1 << (31 - bitIdx)); // PWMWaveform[wordOffset] |= (1 << bitIdx); break; case 0: PWMWaveform[wordOffset] &= ~(1 << (31 - bitIdx)); // PWMWaveform[wordOffset] &= ~(1 << bitIdx); break; } } // Get an individual bit from the PWM output array, accounting for word boundaries unsigned char getPWMBit(unsigned int bitPos) { // Fetch word the bit is in unsigned int wordOffset = (int)(bitPos / 32); unsigned int bitIdx = bitPos - (wordOffset * 32); if(PWMWaveform[wordOffset] & (1 << bitIdx)) { return true; } else { return false; } } // Debug // Dump contents of LED buffer void dumpLEDBuffer(void) { int i; printf("Dumping LED buffer:\n"); for(i=0; i> PWM_DMAC_PANIC) & 0b11111111); printf(" DREQ: %d\n", (pwm_reg[PWM_DMAC] >> PWM_DMAC_DREQ) & 0b11111111); printf("\n"); } // Display all PWM registers void dumpPWM(void) { dumpPWMStatus(); dumpPWMControl(pwm_reg[PWM_CTL]); dumpPWMDMAC(); } // Display all PWM control registers void dumpDMARegs(void) { printf("DMA Registers\n"); printf(" CONBLK_AD: 0x%x (", dma_reg[DMA_CONBLK_AD]); printBinary(dma_reg[DMA_CONBLK_AD], 32); printf(")\n"); printf(" SOURCE_AD: 0x%x\n", dma_reg[DMA_SOURCE_AD]); printf(" DEST_AD: 0x%x\n", dma_reg[DMA_DEST_AD]); printf(" TXFR_LEN: 0x%x\n", dma_reg[DMA_TXFR_LEN]); printf(" NEXTCONBK: 0x%x\n", dma_reg[DMA_NEXTCONBK]); printf(" STRIDE: 0x%x\n", dma_reg[DMA_STRIDE]); printf(" TI: 0x%x\n", dma_reg[DMA_TI]); printf(" CS: 0x%x\n", dma_reg[DMA_CS]); printf(" DEBUG: 0x%x\n", dma_reg[DMA_DEBUG]); printf("\n"); } // Display the contents of a Control Block void dumpControlBlock(dma_cb_t *c) { printf("Control Block\n"); printf(" TI: 0x%x\n", c->info); printf(" SOURCE_AD: 0x%x\n", c->src); printf(" DEST_AD: 0x%x\n", c->dst); printf(" TXFR_LEN: 0x%x\n", c->length); printf(" STRIDE: 0x%x\n", c->stride); printf(" NEXTCONBK: 0x%x\n", c->next); printf(" RES1: 0x%x\n", c->pad[0]); printf(" RES2: 0x%x\n", c->pad[1]); printf("\n"); } // Display the contents of a Transfer Information word void dumpTransferInformation(unsigned int TI) { printf("Transfer Information (0x%x, ", TI); printBinary(TI, 32); printf(")\n"); printf(" NO_WIDE_BURSTS: %d\n", GETBIT(TI, DMA_TI_NO_WIDE_BURSTS)); printf(" WAITS: %d\n", (TI >> DMA_TI_WAITS) & 0b11111); // WAITS is bits 25:21 printf(" PERMAP: %d\n", (TI >> DMA_TI_PERMAP) & 0b11111); // PERMAP is bits 20:16 printf(" BURST_LENGTH: %d\n", (TI >> DMA_TI_BURST_LENGTH) & 0b1111); // BURST_LENGTH is bits 15:12 printf(" SRC_IGNORE: %d\n", GETBIT(TI, DMA_TI_SRC_IGNORE)); printf(" SRC_DREQ: %d\n", GETBIT(TI, DMA_TI_SRC_DREQ)); printf(" SRC_WIDTH: %d\n", GETBIT(TI, DMA_TI_SRC_WIDTH)); printf(" SRC_INC: %d\n", GETBIT(TI, DMA_TI_SRC_INC)); printf(" DEST_IGNORE: %d\n", GETBIT(TI, DMA_TI_DEST_IGNORE)); printf(" DEST_DREQ: %d\n", GETBIT(TI, DMA_TI_DEST_DREQ)); printf(" DEST_WIDTH: %d\n", GETBIT(TI, DMA_TI_DEST_WIDTH)); printf(" DEST_INC: %d\n", GETBIT(TI, DMA_TI_DEST_INC)); printf(" WAIT_RESP: %d\n", GETBIT(TI, DMA_TI_WAIT_RESP)); printf(" TDMODE: %d\n", GETBIT(TI, DMA_TI_TDMODE)); printf(" INTEN: %d\n", GETBIT(TI, DMA_TI_INTEN)); printf("\n"); } // Display the readable DMA registers void dumpDMA(void) { dumpDMARegs(); printf("DMA Control & Status Register: "); printBinary(dma_reg[DMA_CS], 32); printf("\n"); printf(" RESET: %d\n", GETBIT(dma_reg[DMA_CS], DMA_CS_RESET)); printf(" ABORT: %d\n", GETBIT(dma_reg[DMA_CS], DMA_CS_ABORT)); printf(" DISDEBUG: %d\n", GETBIT(dma_reg[DMA_CS], DMA_CS_DISDEBUG)); printf(" PANIC_PRI: %d\n", (dma_reg[DMA_CS] >> DMA_CS_PANIC_PRI) & 0b1111); printf(" PRIORITY: %d\n", (dma_reg[DMA_CS] >> DMA_CS_PRIORITY) & 0b1111); printf(" ERROR: %d\n", GETBIT(dma_reg[DMA_CS], DMA_CS_ERROR)); printf(" WAITING_FOR: %d\n", GETBIT(dma_reg[DMA_CS], DMA_CS_WAITING_FOR)); printf(" DREQ_STOPS_DMA: %d\n", GETBIT(dma_reg[DMA_CS], DMA_CS_DREQ_STOPS_DMA)); printf(" PAUSED: %d\n", GETBIT(dma_reg[DMA_CS], DMA_CS_PAUSED)); printf(" DREQ: %d\n", GETBIT(dma_reg[DMA_CS], DMA_CS_DREQ)); printf(" INT: %d\n", GETBIT(dma_reg[DMA_CS], DMA_CS_INT)); printf(" END: %d\n", GETBIT(dma_reg[DMA_CS], DMA_CS_END)); printf(" ACTIVE: %d\n", GETBIT(dma_reg[DMA_CS], DMA_CS_ACTIVE)); printf("\n"); dumpTransferInformation(dma_reg[DMA_TI]); printf("DMA Debug Register: "); printBinary(dma_reg[DMA_DEBUG], 32); printf("\n"); printf(" LITE: %d\n", GETBIT(dma_reg[DMA_DEBUG], DMA_DEBUG_LITE)); printf(" VERSION: %d\n", (dma_reg[DMA_DEBUG] >> DMA_DEBUG_VERSION) & 0b1111); printf(" DMA_STATE: %d\n", (dma_reg[DMA_DEBUG] >> DMA_DEBUG_DMA_STATE) & 0b111111111); printf(" DMA_ID: %d\n", (dma_reg[DMA_DEBUG] >> DMA_DEBUG_DMA_ID) & 0b11111111); printf(" OUTSTANDING W: %d\n", (dma_reg[DMA_DEBUG] >> DMA_DEBUG_OUTSTANDING_WRITES) & 0b1111); printf(" READ_ERROR: %d\n", GETBIT(dma_reg[DMA_DEBUG], DMA_DEBUG_READ_ERROR)); printf(" FIFO_ERROR: %d\n", GETBIT(dma_reg[DMA_DEBUG], DMA_DEBUG_FIFO_ERROR)); printf(" READ_LAST_NS: %d\n", GETBIT(dma_reg[DMA_DEBUG], DMA_DEBUG_READ_LAST_NOT_SET)); printf("\n"); } // Init Hardware void init(int numPixels) { numLEDs = numPixels; brightness = DEFAULT_BRIGHTNESS; initHardware(); } void initHardware(void) { int i = 0; int pid; int fd; char pagemap_fn[64]; // Clear the PWM buffer // --------------------------------------------------------------- clearPWMBuffer(); // Set up peripheral access // --------------------------------------------------------------- dma_reg = map_peripheral(DMA_BASE, DMA_LEN); dma_reg += 0x000; pwm_reg = map_peripheral(PWM_BASE, PWM_LEN); clk_reg = map_peripheral(CLK_BASE, CLK_LEN); gpio_reg = map_peripheral(GPIO_BASE, GPIO_LEN); // Set PWM alternate function for GPIO18 // --------------------------------------------------------------- //gpio_reg[1] &= ~(7 << 24); //usleep(100); //gpio_reg[1] |= (2 << 24); //usleep(100); SET_GPIO_ALT(18, 5); // Allocate memory for the DMA control block & data to be sent // --------------------------------------------------------------- virtbase = mmap( NULL, // Address NUM_PAGES * PAGE_SIZE, // Length PROT_READ | PROT_WRITE, // Protection MAP_SHARED | // Shared MAP_ANONYMOUS | // Not file-based, init contents to 0 MAP_NORESERVE | // Don't reserve swap space MAP_LOCKED, // Lock in RAM (don't swap) -1, // File descriptor 0); // Offset if (virtbase == MAP_FAILED) { fatal("Failed to mmap physical pages: %m\n"); } if ((unsigned long)virtbase & (PAGE_SIZE-1)) { fatal("Virtual address is not page aligned\n"); } //printf("virtbase mapped 0x%x bytes at 0x%x\n", NUM_PAGES * PAGE_SIZE, virtbase); // Allocate page map (pointers to the control block(s) and data for each CB page_map = malloc(NUM_PAGES * sizeof(*page_map)); if (page_map == 0) { fatal("Failed to malloc page_map: %m\n"); } else { //printf("Allocated 0x%x bytes for page_map at 0x%x\n", NUM_PAGES * sizeof(*page_map), page_map); } // Use /proc/self/pagemap to figure out the mapping between virtual and physical addresses pid = getpid(); sprintf(pagemap_fn, "/proc/%d/pagemap", pid); fd = open(pagemap_fn, O_RDONLY); if (fd < 0) { fatal("Failed to open %s: %m\n", pagemap_fn); } if (lseek(fd, (unsigned long)virtbase >> 9, SEEK_SET) != (unsigned long)virtbase >> 9) { fatal("Failed to seek on %s: %m\n", pagemap_fn); } //printf("Page map: %d pages\n", NUM_PAGES); for (i = 0; i < NUM_PAGES; i++) { uint64_t pfn; page_map[i].virtaddr = virtbase + i * PAGE_SIZE; // Following line forces page to be allocated // (Note: Copied directly from Hirst's code... page_map[i].virtaddr[0] was just set...?) page_map[i].virtaddr[0] = 0; if (read(fd, &pfn, sizeof(pfn)) != sizeof(pfn)) { fatal("Failed to read %s: %m\n", pagemap_fn); } if ((pfn >> 55)&0xfbf != 0x10c) { // pagemap bits: https://www.kernel.org/doc/Documentation/vm/pagemap.txt fatal("Page %d not present (pfn 0x%016llx)\n", i, pfn); } page_map[i].physaddr = (unsigned int)pfn << PAGE_SHIFT | 0x40000000; //printf("Page map #%2d: virtual %8p ==> physical 0x%08x [0x%016llx]\n", i, page_map[i].virtaddr, page_map[i].physaddr, pfn); } // Set up control block // --------------------------------------------------------------- ctl = (struct control_data_s *)virtbase; dma_cb_t *cbp = ctl->cb; // FIXME: Change this to use DEFINEs unsigned int phys_pwm_fifo_addr = 0x7e20c000 + 0x18; // No wide bursts, source increment, dest DREQ on line 5, wait for response, enable interrupt cbp->info = DMA_TI_CONFIGWORD; // Source is our allocated memory cbp->src = mem_virt_to_phys(ctl->sample); // Destination is the PWM controller cbp->dst = phys_pwm_fifo_addr; // 72 bits per pixel / 32 bits per word = 2.25 words per pixel // Add 1 to make sure the PWM FIFO gets the message: "we're sending zeroes" // Times 4 because DMA works in bytes, not words cbp->length = ((numLEDs * 2.25) + 1) * 4; if(cbp->length > NUM_DATA_WORDS * 4) { cbp->length = NUM_DATA_WORDS * 4; } // We don't use striding cbp->stride = 0; // These are reserved cbp->pad[0] = 0; cbp->pad[1] = 0; // Pointer to next block - 0 shuts down the DMA channel when transfer is complete cbp->next = 0; // Testing /* ctl = (struct control_data_s *)virtbase; ctl->sample[0] = 0x00000000; ctl->sample[1] = 0x000000FA; ctl->sample[2] = 0x0000FFFF; ctl->sample[3] = 0xAAAAAAAA; ctl->sample[4] = 0xF0F0F0F0; ctl->sample[5] = 0x0A0A0A0A; ctl->sample[6] = 0xF00F0000; */ // Stop any existing DMA transfers // --------------------------------------------------------------- dma_reg[DMA_CS] |= (1 << DMA_CS_ABORT); usleep(100); dma_reg[DMA_CS] = (1 << DMA_CS_RESET); usleep(100); // PWM Clock // --------------------------------------------------------------- // Kill the clock // FIXME: Change this to use a DEFINE clk_reg[PWM_CLK_CNTL] = 0x5A000000 | (1 << 5); usleep(100); // Disable DMA requests CLRBIT(pwm_reg[PWM_DMAC], PWM_DMAC_ENAB); usleep(100); // The fractional part is quantized to a range of 0-1024, so multiply the decimal part by 1024. // E.g., 0.25 * 1024 = 256. // So, if you want a divisor of 400.5, set idiv to 400 and fdiv to 512. unsigned int idiv = 400; unsigned short fdiv = 0; // Should be 16 bits, but the value must be <= 1024 clk_reg[PWM_CLK_DIV] = 0x5A000000 | (idiv << 12) | fdiv; // Set clock multiplier usleep(100); // Enable the clock. Next-to-last digit means "enable clock". Last digit is 1 (oscillator), // 4 (PLLA), 5 (PLLC), or 6 (PLLD) (according to the docs) although PLLA doesn't seem to work. // FIXME: Change this to use a DEFINE clk_reg[PWM_CLK_CNTL] = 0x5A000015; usleep(100); // PWM // --------------------------------------------------------------- // Clear any preexisting crap from the control & status register pwm_reg[PWM_CTL] = 0; // Set transmission range (32 bytes, or 1 word) // <32: Truncate. >32: Pad with SBIT1. As it happens, 32 is perfect. pwm_reg[PWM_RNG1] = 32; usleep(100); // Send DMA requests to fill the FIFO pwm_reg[PWM_DMAC] = (1 << PWM_DMAC_ENAB) | (8 << PWM_DMAC_PANIC) | (8 << PWM_DMAC_DREQ); usleep(1000); // Clear the FIFO SETBIT(pwm_reg[PWM_CTL], PWM_CTL_CLRF1); usleep(100); // Don't repeat last FIFO contents if it runs dry CLRBIT(pwm_reg[PWM_CTL], PWM_CTL_RPTL1); usleep(100); // Silence (default) bit is 0 CLRBIT(pwm_reg[PWM_CTL], PWM_CTL_SBIT1); usleep(100); // Polarity = default (low = 0, high = 1) CLRBIT(pwm_reg[PWM_CTL], PWM_CTL_POLA1); usleep(100); // Enable serializer mode SETBIT(pwm_reg[PWM_CTL], PWM_CTL_MODE1); usleep(100); // Use FIFO rather than DAT1 SETBIT(pwm_reg[PWM_CTL], PWM_CTL_USEF1); usleep(100); // Disable MSEN1 CLRBIT(pwm_reg[PWM_CTL], PWM_CTL_MSEN1); usleep(100); // DMA // --------------------------------------------------------------- // Raise an interrupt when transfer is complete, which will set the INT flag in the CS register SETBIT(dma_reg[DMA_CS], DMA_CS_INT); usleep(100); // Clear the END flag (by setting it - this is a "write 1 to clear", or W1C, bit) SETBIT(dma_reg[DMA_CS], DMA_CS_END); usleep(100); // Send the physical address of the control block into the DMA controller dma_reg[DMA_CONBLK_AD] = mem_virt_to_phys(ctl->cb); usleep(100); // Clear error flags, if any (these are also W1C bits) // FIXME: Use a define instead of this dma_reg[DMA_DEBUG] = 7; usleep(100); } // Begin the transfer void startTransfer(void) { #ifdef RPI2 #warning "Pi 2 hack enabled" // Force buffer clear // Temp Pi2 fix, thanks Jon! char* buffer; buffer=(char*)malloc(1024*1024); memset(buffer, 0, 1024*1024); free(buffer); #endif // Enable DMA dma_reg[DMA_CONBLK_AD] = mem_virt_to_phys(ctl->cb); dma_reg[DMA_CS] = DMA_CS_CONFIGWORD | (1 << DMA_CS_ACTIVE); usleep(100); // Enable PWM SETBIT(pwm_reg[PWM_CTL], PWM_CTL_PWEN1); // dumpPWM(); // dumpDMA(); } // Update LEDs void show(void) { // Clear out the PWM buffer // Disabled, because we will overwrite the buffer anyway. // Read data from LEDBuffer[], translate it into wire format, and write to PWMWaveform int i, j; unsigned int LEDBuffeWordPos = 0; unsigned int PWMWaveformBitPos = 0; unsigned int colorBits = 0; // Holds the GRB color before conversion to wire bit pattern unsigned char colorBit = 0; // Holds current bit out of colorBits to be processed unsigned int wireBit = 0; // Holds the current bit we will set in PWMWaveform Color_t color; for(i=0; i=0; j--) { colorBit = (colorBits & (1 << j)) ? 1 : 0; switch(colorBit) { case 1: //wireBits = 0b110; // High, High, Low setPWMBit(wireBit++, 1); setPWMBit(wireBit++, 1); setPWMBit(wireBit++, 0); break; case 0: //wireBits = 0b100; // High, Low, Low setPWMBit(wireBit++, 1); setPWMBit(wireBit++, 0); setPWMBit(wireBit++, 0); break; } } } // Copy PWM waveform to DMA's data buffer //printf("Copying %d words to DMA data buffer\n", NUM_DATA_WORDS); ctl = (struct control_data_s *)virtbase; dma_cb_t *cbp = ctl->cb; // This block is a major CPU hog when there are lots of pixels to be transmitted. // It would go quicker with DMA. for(i = 0; i < (cbp->length / 4); i++) { ctl->sample[i] = PWMWaveform[i]; } // Enable DMA and PWM engines, which should now send the data startTransfer(); // Wait long enough for the DMA transfer to finish // 3 RAM bits per wire bit, so 72 bits to send one color command. float bitTimeUSec = (float)(NUM_DATA_WORDS * 32) * 0.4; // Bits sent * time to transmit one bit, which is 0.4μSec //printf("Delay for %d μSec\n", (int)bitTimeUSec); usleep((int)bitTimeUSec); /* This is the old FIFO-filling code. The FIFO only has enough words for about 7 LEDs, which is why we use DMA instead! for(i=0; i * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * 3. Neither the name of the owner nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include #include #include #include #include #include #include #include #include #include #include "mailbox.h" #include "clk.h" #include "gpio.h" #include "dma.h" #include "pwm.h" #include "rpihw.h" #include "gamma.h" #include "ws2811.h" #define BUS_TO_PHYS(x) ((x)&~0xC0000000) #define OSC_FREQ 19200000 // crystal frequency /* 3 colors, 8 bits per byte, 3 symbols per bit + 55uS low for reset signal */ #define LED_RESET_uS 55 #define LED_BIT_COUNT(leds, freq) ((leds * 3 * 8 * 3) + ((LED_RESET_uS * \ (freq * 3)) / 1000000)) // Pad out to the nearest uint32 + 32-bits for idle low/high times the number of channels #define PWM_BYTE_COUNT(leds, freq) (((((LED_BIT_COUNT(leds, freq) >> 3) & ~0x7) + 4) + 4) * \ RPI_PWM_CHANNELS) #define SYMBOL_HIGH 0x6 // 1 1 0 #define SYMBOL_LOW 0x4 // 1 0 0 #define ARRAY_SIZE(stuff) (sizeof(stuff) / sizeof(stuff[0])) // We use the mailbox interface to request memory from the VideoCore. // This lets us request one physically contiguous chunk, find its // physical address, and map it 'uncached' so that writes from this // code are immediately visible to the DMA controller. This struct // holds data relevant to the mailbox interface. typedef struct videocore_mbox { int handle; /* From mbox_open() */ unsigned mem_ref; /* From mem_alloc() */ unsigned bus_addr; /* From mem_lock() */ unsigned size; /* Size of allocation */ uint8_t *virt_addr; /* From mapmem() */ } videocore_mbox_t; typedef struct ws2811_device { volatile uint8_t *pwm_raw; volatile dma_t *dma; volatile pwm_t *pwm; volatile dma_cb_t *dma_cb; uint32_t dma_cb_addr; volatile gpio_t *gpio; volatile cm_pwm_t *cm_pwm; videocore_mbox_t mbox; int max_count; } ws2811_device_t; /** * Iterate through the channels and find the largest led count. * * @param ws2811 ws2811 instance pointer. * * @returns Maximum number of LEDs in all channels. */ static int max_channel_led_count(ws2811_t *ws2811) { int chan, max = 0; for (chan = 0; chan < RPI_PWM_CHANNELS; chan++) { if (ws2811->channel[chan].count > max) { max = ws2811->channel[chan].count; } } return max; } /** * Map all devices into userspace memory. * * @param ws2811 ws2811 instance pointer. * * @returns 0 on success, -1 otherwise. */ static int map_registers(ws2811_t *ws2811) { ws2811_device_t *device = ws2811->device; const rpi_hw_t *rpi_hw = ws2811->rpi_hw; uint32_t base = ws2811->rpi_hw->periph_base; uint32_t dma_addr; dma_addr = dmanum_to_offset(ws2811->dmanum); if (!dma_addr) { return -1; } dma_addr += rpi_hw->periph_base; device->dma = mapmem(dma_addr, sizeof(dma_t)); if (!device->dma) { return -1; } device->pwm = mapmem(PWM_OFFSET + base, sizeof(pwm_t)); if (!device->pwm) { return -1; } device->gpio = mapmem(GPIO_OFFSET + base, sizeof(gpio_t)); if (!device->gpio) { return -1; } device->cm_pwm = mapmem(CM_PWM_OFFSET + base, sizeof(cm_pwm_t)); if (!device->cm_pwm) { return -1; } return 0; } /** * Unmap all devices from virtual memory. * * @param ws2811 ws2811 instance pointer. * * @returns None */ static void unmap_registers(ws2811_t *ws2811) { ws2811_device_t *device = ws2811->device; if (device->dma) { unmapmem((void *)device->dma, sizeof(dma_t)); } if (device->pwm) { unmapmem((void *)device->pwm, sizeof(pwm_t)); } if (device->cm_pwm) { unmapmem((void *)device->cm_pwm, sizeof(cm_pwm_t)); } if (device->gpio) { unmapmem((void *)device->gpio, sizeof(gpio_t)); } } /** * Given a userspace address pointer, return the matching bus address used by DMA. * Note: The bus address is not the same as the CPU physical address. * * @param addr Userspace virtual address pointer. * * @returns Bus address for use by DMA. */ static uint32_t addr_to_bus(ws2811_device_t *device, const volatile void *virt) { videocore_mbox_t *mbox = &device->mbox; uint32_t offset = (uint8_t *)virt - mbox->virt_addr; return mbox->bus_addr + offset; } /** * Stop the PWM controller. * * @param ws2811 ws2811 instance pointer. * * @returns None */ static void stop_pwm(ws2811_t *ws2811) { ws2811_device_t *device = ws2811->device; volatile pwm_t *pwm = device->pwm; volatile cm_pwm_t *cm_pwm = device->cm_pwm; // Turn off the PWM in case already running pwm->ctl = 0; usleep(10); // Kill the clock if it was already running cm_pwm->ctl = CM_PWM_CTL_PASSWD | CM_PWM_CTL_KILL; usleep(10); while (cm_pwm->ctl & CM_PWM_CTL_BUSY) ; } /** * Setup the PWM controller in serial mode on both channels using DMA to feed the PWM FIFO. * * @param ws2811 ws2811 instance pointer. * * @returns None */ static int setup_pwm(ws2811_t *ws2811) { ws2811_device_t *device = ws2811->device; volatile dma_t *dma = device->dma; volatile dma_cb_t *dma_cb = device->dma_cb; volatile pwm_t *pwm = device->pwm; volatile cm_pwm_t *cm_pwm = device->cm_pwm; int maxcount = max_channel_led_count(ws2811); uint32_t freq = ws2811->freq; int32_t byte_count; stop_pwm(ws2811); // Setup the PWM Clock - Use OSC @ 19.2Mhz w/ 3 clocks/tick cm_pwm->div = CM_PWM_DIV_PASSWD | CM_PWM_DIV_DIVI(OSC_FREQ / (3 * freq)); cm_pwm->ctl = CM_PWM_CTL_PASSWD | CM_PWM_CTL_SRC_OSC; cm_pwm->ctl = CM_PWM_CTL_PASSWD | CM_PWM_CTL_SRC_OSC | CM_PWM_CTL_ENAB; usleep(10); while (!(cm_pwm->ctl & CM_PWM_CTL_BUSY)) ; // Setup the PWM, use delays as the block is rumored to lock up without them. Make // sure to use a high enough priority to avoid any FIFO underruns, especially if // the CPU is busy doing lots of memory accesses, or another DMA controller is // busy. The FIFO will clock out data at a much slower rate (2.6Mhz max), so // the odds of a DMA priority boost are extremely low. pwm->rng1 = 32; // 32-bits per word to serialize usleep(10); pwm->ctl = RPI_PWM_CTL_CLRF1; usleep(10); pwm->dmac = RPI_PWM_DMAC_ENAB | RPI_PWM_DMAC_PANIC(7) | RPI_PWM_DMAC_DREQ(3); usleep(10); pwm->ctl = RPI_PWM_CTL_USEF1 | RPI_PWM_CTL_MODE1 | RPI_PWM_CTL_USEF2 | RPI_PWM_CTL_MODE2; if (ws2811->channel[0].invert) { pwm->ctl |= RPI_PWM_CTL_POLA1; } if (ws2811->channel[1].invert) { pwm->ctl |= RPI_PWM_CTL_POLA2; } usleep(10); pwm->ctl |= RPI_PWM_CTL_PWEN1 | RPI_PWM_CTL_PWEN2; // Initialize the DMA control block byte_count = PWM_BYTE_COUNT(maxcount, freq); dma_cb->ti = RPI_DMA_TI_NO_WIDE_BURSTS | // 32-bit transfers RPI_DMA_TI_WAIT_RESP | // wait for write complete RPI_DMA_TI_DEST_DREQ | // user peripheral flow control RPI_DMA_TI_PERMAP(5) | // PWM peripheral RPI_DMA_TI_SRC_INC; // Increment src addr dma_cb->source_ad = addr_to_bus(device, device->pwm_raw); dma_cb->dest_ad = (uint32_t)&((pwm_t *)PWM_PERIPH_PHYS)->fif1; dma_cb->txfr_len = byte_count; dma_cb->stride = 0; dma_cb->nextconbk = 0; dma->cs = 0; dma->txfr_len = 0; return 0; } /** * Start the DMA feeding the PWM FIFO. This will stream the entire DMA buffer out of both * PWM channels. * * @param ws2811 ws2811 instance pointer. * * @returns None */ static void dma_start(ws2811_t *ws2811) { ws2811_device_t *device = ws2811->device; volatile dma_t *dma = device->dma; uint32_t dma_cb_addr = device->dma_cb_addr; dma->cs = RPI_DMA_CS_RESET; usleep(10); dma->cs = RPI_DMA_CS_INT | RPI_DMA_CS_END; usleep(10); dma->conblk_ad = dma_cb_addr; dma->debug = 7; // clear debug error flags dma->cs = RPI_DMA_CS_WAIT_OUTSTANDING_WRITES | RPI_DMA_CS_PANIC_PRIORITY(15) | RPI_DMA_CS_PRIORITY(15) | RPI_DMA_CS_ACTIVE; } /** * Initialize the application selected GPIO pins for PWM operation. * * @param ws2811 ws2811 instance pointer. * * @returns 0 on success, -1 on unsupported pin */ static int gpio_init(ws2811_t *ws2811) { volatile gpio_t *gpio = ws2811->device->gpio; int chan; for (chan = 0; chan < RPI_PWM_CHANNELS; chan++) { int pinnum = ws2811->channel[chan].gpionum; if (pinnum) { int altnum = pwm_pin_alt(chan, pinnum); if (altnum < 0) { return -1; } gpio_function_set(gpio, pinnum, altnum); } } return 0; } /** * Initialize the PWM DMA buffer with all zeros, inverted operation will be * handled by hardware. The DMA buffer length is assumed to be a word * multiple. * * @param ws2811 ws2811 instance pointer. * * @returns None */ void pwm_raw_init(ws2811_t *ws2811) { volatile uint32_t *pwm_raw = (uint32_t *)ws2811->device->pwm_raw; int maxcount = max_channel_led_count(ws2811); int wordcount = (PWM_BYTE_COUNT(maxcount, ws2811->freq) / sizeof(uint32_t)) / RPI_PWM_CHANNELS; int chan; for (chan = 0; chan < RPI_PWM_CHANNELS; chan++) { int i, wordpos = chan; for (i = 0; i < wordcount; i++) { pwm_raw[wordpos] = 0x0; wordpos += 2; } } } /** * Cleanup previously allocated device memory and buffers. * * @param ws2811 ws2811 instance pointer. * * @returns None */ void ws2811_cleanup(ws2811_t *ws2811) { ws2811_device_t *device = ws2811->device; int chan; for (chan = 0; chan < RPI_PWM_CHANNELS; chan++) { if (ws2811->channel[chan].leds) { free(ws2811->channel[chan].leds); } ws2811->channel[chan].leds = NULL; } if (device->mbox.handle != -1) { videocore_mbox_t *mbox = &device->mbox; unmapmem(mbox->virt_addr, mbox->size); mem_unlock(mbox->handle, mbox->mem_ref); mem_free(mbox->handle, mbox->mem_ref); mbox_close(mbox->handle); mbox->handle = -1; } if (device) { free(device); } ws2811->device = NULL; } /* * * Application API Functions * */ /** * Allocate and initialize memory, buffers, pages, PWM, DMA, and GPIO. * * @param ws2811 ws2811 instance pointer. * * @returns 0 on success, -1 otherwise. */ int ws2811_init(ws2811_t *ws2811) { ws2811_device_t *device; const rpi_hw_t *rpi_hw; int chan; ws2811->rpi_hw = rpi_hw_detect(); if (!ws2811->rpi_hw) { return -1; } rpi_hw = ws2811->rpi_hw; ws2811->device = malloc(sizeof(*ws2811->device)); if (!ws2811->device) { return -1; } device = ws2811->device; // Determine how much physical memory we need for DMA device->mbox.size = PWM_BYTE_COUNT(max_channel_led_count(ws2811), ws2811->freq) + sizeof(dma_cb_t); // Round up to page size multiple device->mbox.size = (device->mbox.size + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1); device->mbox.handle = mbox_open(); if (device->mbox.handle == -1) { return -1; } device->mbox.mem_ref = mem_alloc(device->mbox.handle, device->mbox.size, PAGE_SIZE, rpi_hw->videocore_base == 0x40000000 ? 0xC : 0x4); if (device->mbox.mem_ref == 0) { return -1; } device->mbox.bus_addr = mem_lock(device->mbox.handle, device->mbox.mem_ref); if (device->mbox.bus_addr == (uint32_t) ~0UL) { mem_free(device->mbox.handle, device->mbox.size); return -1; } device->mbox.virt_addr = mapmem(BUS_TO_PHYS(device->mbox.bus_addr), device->mbox.size); // Initialize all pointers to NULL. Any non-NULL pointers will be freed on cleanup. device->pwm_raw = NULL; device->dma_cb = NULL; for (chan = 0; chan < RPI_PWM_CHANNELS; chan++) { ws2811->channel[chan].leds = NULL; } // Allocate the LED buffers for (chan = 0; chan < RPI_PWM_CHANNELS; chan++) { ws2811_channel_t *channel = &ws2811->channel[chan]; channel->leds = malloc(sizeof(ws2811_led_t) * channel->count); if (!channel->leds) { goto err; } memset(channel->leds, 0, sizeof(ws2811_led_t) * channel->count); if (!channel->strip_type) { channel->strip_type=WS2811_STRIP_RGB; } } device->dma_cb = (dma_cb_t *)device->mbox.virt_addr; device->pwm_raw = (uint8_t *)device->mbox.virt_addr + sizeof(dma_cb_t); pwm_raw_init(ws2811); memset((dma_cb_t *)device->dma_cb, 0, sizeof(dma_cb_t)); // Cache the DMA control block bus address device->dma_cb_addr = addr_to_bus(device, device->dma_cb); // Map the physical registers into userspace if (map_registers(ws2811)) { goto err; } // Initialize the GPIO pins if (gpio_init(ws2811)) { unmap_registers(ws2811); goto err; } // Setup the PWM, clocks, and DMA if (setup_pwm(ws2811)) { unmap_registers(ws2811); goto err; } return 0; err: ws2811_cleanup(ws2811); return -1; } /** * Shut down DMA, PWM, and cleanup memory. * * @param ws2811 ws2811 instance pointer. * * @returns None */ void ws2811_fini(ws2811_t *ws2811) { ws2811_wait(ws2811); stop_pwm(ws2811); unmap_registers(ws2811); ws2811_cleanup(ws2811); } /** * Wait for any executing DMA operation to complete before returning. * * @param ws2811 ws2811 instance pointer. * * @returns 0 on success, -1 on DMA competion error */ int ws2811_wait(ws2811_t *ws2811) { volatile dma_t *dma = ws2811->device->dma; while ((dma->cs & RPI_DMA_CS_ACTIVE) && !(dma->cs & RPI_DMA_CS_ERROR)) { usleep(10); } if (dma->cs & RPI_DMA_CS_ERROR) { fprintf(stderr, "DMA Error: %08x\n", dma->debug); return -1; } return 0; } /** * Render the PWM DMA buffer from the user supplied LED arrays and start the DMA * controller. This will update all LEDs on both PWM channels. * * @param ws2811 ws2811 instance pointer. * * @returns None */ int ws2811_render(ws2811_t *ws2811) { volatile uint8_t *pwm_raw = ws2811->device->pwm_raw; int bitpos = 31; int i, k, l, chan; unsigned j; for (chan = 0; chan < RPI_PWM_CHANNELS; chan++) // Channel { ws2811_channel_t *channel = &ws2811->channel[chan]; int wordpos = chan; int scale = (channel->brightness & 0xff) + 1; int rshift = (channel->strip_type >> 16) & 0xff; int gshift = (channel->strip_type >> 8) & 0xff; int bshift = (channel->strip_type >> 0) & 0xff; for (i = 0; i < channel->count; i++) // Led { uint8_t color[] = { ws281x_gamma[(((channel->leds[i] >> rshift) & 0xff) * scale) >> 8], // red ws281x_gamma[(((channel->leds[i] >> gshift) & 0xff) * scale) >> 8], // green ws281x_gamma[(((channel->leds[i] >> bshift) & 0xff) * scale) >> 8], // blue }; for (j = 0; j < ARRAY_SIZE(color); j++) // Color { for (k = 7; k >= 0; k--) // Bit { uint8_t symbol = SYMBOL_LOW; if (color[j] & (1 << k)) { symbol = SYMBOL_HIGH; } for (l = 2; l >= 0; l--) // Symbol { uint32_t *wordptr = &((uint32_t *)pwm_raw)[wordpos]; *wordptr &= ~(1 << bitpos); if (symbol & (1 << l)) { *wordptr |= (1 << bitpos); } bitpos--; if (bitpos < 0) { // Every other word is on the same channel wordpos += 2; bitpos = 31; } } } } } } // Wait for any previous DMA operation to complete. if (ws2811_wait(ws2811)) { return -1; } dma_start(ws2811); return 0; } ./library/legacy/rpi-ws281x/lib/dma.h0000664000175000017500000001272514223621661020407 0ustar jawn-smithjawn-smith/* * dma.h * * Copyright (c) 2014 Jeremy Garff * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * 3. Neither the name of the owner nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef __DMA_H__ #define __DMA_H__ /* * DMA Control Block in Main Memory * * Note: Must start at a 256 byte aligned address. * Use corresponding register field definitions. */ typedef struct { uint32_t ti; uint32_t source_ad; uint32_t dest_ad; uint32_t txfr_len; uint32_t stride; uint32_t nextconbk; uint32_t resvd_0x18[2]; } __attribute__((packed)) dma_cb_t; /* * DMA register set */ typedef struct { uint32_t cs; #define RPI_DMA_CS_RESET (1 << 31) #define RPI_DMA_CS_ABORT (1 << 30) #define RPI_DMA_CS_DISDEBUG (1 << 29) #define RPI_DMA_CS_WAIT_OUTSTANDING_WRITES (1 << 28) #define RPI_DMA_CS_PANIC_PRIORITY(val) ((val & 0xf) << 20) #define RPI_DMA_CS_PRIORITY(val) ((val & 0xf) << 16) #define RPI_DMA_CS_ERROR (1 << 8) #define RPI_DMA_CS_WAITING_OUTSTANDING_WRITES (1 << 6) #define RPI_DMA_CS_DREQ_STOPS_DMA (1 << 5) #define RPI_DMA_CS_PAUSED (1 << 4) #define RPI_DMA_CS_DREQ (1 << 3) #define RPI_DMA_CS_INT (1 << 2) #define RPI_DMA_CS_END (1 << 1) #define RPI_DMA_CS_ACTIVE (1 << 0) uint32_t conblk_ad; uint32_t ti; #define RPI_DMA_TI_NO_WIDE_BURSTS (1 << 26) #define RPI_DMA_TI_WAITS(val) ((val & 0x1f) << 21) #define RPI_DMA_TI_PERMAP(val) ((val & 0x1f) << 16) #define RPI_DMA_TI_BURST_LENGTH(val) ((val & 0xf) << 12) #define RPI_DMA_TI_SRC_IGNORE (1 << 11) #define RPI_DMA_TI_SRC_DREQ (1 << 10) #define RPI_DMA_TI_SRC_WIDTH (1 << 9) #define RPI_DMA_TI_SRC_INC (1 << 8) #define RPI_DMA_TI_DEST_IGNORE (1 << 7) #define RPI_DMA_TI_DEST_DREQ (1 << 6) #define RPI_DMA_TI_DEST_WIDTH (1 << 5) #define RPI_DMA_TI_DEST_INC (1 << 4) #define RPI_DMA_TI_WAIT_RESP (1 << 3) #define RPI_DMA_TI_TDMODE (1 << 1) #define RPI_DMA_TI_INTEN (1 << 0) uint32_t source_ad; uint32_t dest_ad; uint32_t txfr_len; #define RPI_DMA_TXFR_LEN_YLENGTH(val) ((val & 0xffff) << 16) #define RPI_DMA_TXFR_LEN_XLENGTH(val) ((val & 0xffff) << 0) uint32_t stride; #define RPI_DMA_STRIDE_D_STRIDE(val) ((val & 0xffff) << 16) #define RPI_DMA_STRIDE_S_STRIDE(val) ((val & 0xffff) << 0) uint32_t nextconbk; uint32_t debug; } __attribute__((packed)) dma_t; #define DMA0_OFFSET (0x00007000) #define DMA1_OFFSET (0x00007100) #define DMA2_OFFSET (0x00007200) #define DMA3_OFFSET (0x00007300) #define DMA4_OFFSET (0x00007400) #define DMA5_OFFSET (0x00007500) #define DMA6_OFFSET (0x00007600) #define DMA7_OFFSET (0x00007700) #define DMA8_OFFSET (0x00007800) #define DMA9_OFFSET (0x00007900) #define DMA10_OFFSET (0x00007a00) #define DMA11_OFFSET (0x00007b00) #define DMA12_OFFSET (0x00007c00) #define DMA13_OFFSET (0x00007d00) #define DMA14_OFFSET (0x00007e00) #define DMA15_OFFSET (0x00e05000) #define PAGE_SIZE (1 << 12) #define PAGE_MASK (~(PAGE_SIZE - 1)) #define PAGE_OFFSET(page) (page & (PAGE_SIZE - 1)) uint32_t dmanum_to_offset(int dmanum); #endif /* __DMA_H__ */ ./library/legacy/rpi-ws281x/lib/clk.h0000664000175000017500000000544514223621661020420 0ustar jawn-smithjawn-smith/* * clk.h * * Copyright (c) 2014 Jeremy Garff * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * 3. Neither the name of the owner nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef __CLK_H__ #define __CLK_H__ typedef struct { uint32_t ctl; #define CM_PWM_CTL_PASSWD (0x5a << 24) #define CM_PWM_CTL_MASH(val) ((val & 0x3) << 9) #define CM_PWM_CTL_FLIP (1 << 8) #define CM_PWM_CTL_BUSY (1 << 7) #define CM_PWM_CTL_KILL (1 << 5) #define CM_PWM_CTL_ENAB (1 << 4) #define CM_PWM_CTL_SRC_GND (0 << 0) #define CM_PWM_CTL_SRC_OSC (1 << 0) #define CM_PWM_CTL_SRC_TSTDBG0 (2 << 0) #define CM_PWM_CTL_SRC_TSTDBG1 (3 << 0) #define CM_PWM_CTL_SRC_PLLA (4 << 0) #define CM_PWM_CTL_SRC_PLLC (5 << 0) #define CM_PWM_CTL_SRC_PLLD (6 << 0) #define CM_PWM_CTL_SRC_HDMIAUX (7 << 0) uint32_t div; #define CM_PWM_DIV_PASSWD (0x5a << 24) #define CM_PWM_DIV_DIVI(val) ((val & 0xfff) << 12) #define CM_PWM_DIV_DIVF(val) ((val & 0xfff) << 0) } __attribute__ ((packed)) cm_pwm_t; #define CM_PWM_OFFSET (0x001010a0) #endif /* __CLK_H__ */ ./library/legacy/rpi-ws281x/lib/README.md0000664000175000017500000000467214223621661020756 0ustar jawn-smithjawn-smithrpi_ws281x ========== Userspace Raspberry Pi PWM library for WS281X LEDs Background: The BCM2835 in the Raspberry Pi has a PWM module that is well suited to driving individually controllable WS281X LEDs. Using the DMA, PWM FIFO, and serial mode in the PWM, it's possible to control almost any number of WS281X LEDs in a chain connected to the PWM output pin. This library and test program set the clock rate of the PWM controller to 3X the desired output frequency and creates a bit pattern in RAM from an array of colors where each bit is represented by 3 bits for the PWM controller as follows. Bit 1 - 1 1 0 Bit 0 - 1 0 0 Hardware: WS281X LEDs are generally driven at 5V, which requires that the data signal be at the same level. Converting the output from a Raspberry Pi GPIO/PWM to a higher voltage through a level shifter is required. It is possible to run the LEDs from a 3.3V - 3.6V power source, and connect the GPIO directly at a cost of brightness, but this isn't recommended. The test program is designed to drive a 8x8 grid of LEDs from Adafruit (http://www.adafruit.com/products/1487). Please see the Adafruit website for more information. Know what you're doing with the hardware and electricity. I take no reponsibility for damage, harm, or mistakes. Build: - Install Scons (on raspbian, apt-get install scons). - Make sure to adjust the parameters in main.c to suit your hardare. - Signal rate (400kHz to 800kHz). Default 800kHz. - ledstring.invert=1 if using a inverting level shifter. - Width and height of LED matrix (height=1 for LED string). - Type 'scons' from inside the source directory. Running: - Type 'sudo scons'. - Type 'sudo ./test'. - That's it. You should see a moving rainbow scroll across the display. Usage: The API is very simple. Make sure to create and initialize the ws2811_t structure as seen in main.c. From there it can be initialized by calling ws2811_init(). LEDs are changed by modifying the color in the .led[index] array and calling ws2811_render(). The rest is handled by the library, which creates the DMA memory and starts the DMA/PWM. Make sure to hook a signal handler for SIGKILL to do cleanup. From the handler make sure to call ws2811_fini(). It'll make sure that the DMA is finished before program execution stops. That's it. Have fun. This was a fun little weekend project. I hope you find it useful. I plan to add some diagrams, waveform scope shots, and a .deb package soon. ./library/legacy/rpi-ws281x/lib/.gitignore0000664000175000017500000000000514223621661021451 0ustar jawn-smithjawn-smithtest ./library/legacy/rpi-ws281x/lib/mailbox.c0000664000175000017500000001634614223621661021277 0ustar jawn-smithjawn-smith/* Copyright (c) 2012, Broadcom Europe Ltd. Copyright (c) 2016, Jeremy Garff All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "mailbox.h" void *mapmem(uint32_t base, uint32_t size) { uint32_t pagemask = ~0UL ^ (getpagesize() - 1); uint32_t offsetmask = getpagesize() - 1; int mem_fd; void *mem; mem_fd = open("/dev/mem", O_RDWR | O_SYNC); if (mem_fd < 0) { perror("Can't open /dev/mem"); return NULL; } mem = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, mem_fd, base & pagemask); if (mem == MAP_FAILED) { perror("mmap error\n"); return NULL; } close(mem_fd); return (char *)mem + (base & offsetmask); } void *unmapmem(void *addr, uint32_t size) { uint32_t pagemask = ~0UL ^ (getpagesize() - 1); uint32_t baseaddr = (uint32_t)addr & pagemask; int s; s = munmap((void *)baseaddr, size); if (s != 0) { perror("munmap error\n"); } return NULL; } /* * use ioctl to send mbox property message */ static int mbox_property(int file_desc, void *buf) { int fd = file_desc; int ret_val = -1; if (fd < 0) { fd = mbox_open(); } if (fd >= 0) { ret_val = ioctl(fd, IOCTL_MBOX_PROPERTY, buf); if (ret_val < 0) { perror("ioctl_set_msg failed\n"); } } if (file_desc < 0) { mbox_close(fd); } return ret_val; } uint32_t mem_alloc(int file_desc, uint32_t size, uint32_t align, uint32_t flags) { int i=0; uint32_t p[32]; p[i++] = 0; // size p[i++] = 0x00000000; // process request p[i++] = 0x3000c; // (the tag id) p[i++] = 12; // (size of the buffer) p[i++] = 12; // (size of the data) p[i++] = size; // (num bytes? or pages?) p[i++] = align; // (alignment) p[i++] = flags; // (MEM_FLAG_L1_NONALLOCATING) p[i++] = 0x00000000; // end tag p[0] = i*sizeof *p; // actual size if (mbox_property(file_desc, p) < 0) return 0; else return p[5]; } uint32_t mem_free(int file_desc, uint32_t handle) { int i=0; uint32_t p[32]; p[i++] = 0; // size p[i++] = 0x00000000; // process request p[i++] = 0x3000f; // (the tag id) p[i++] = 4; // (size of the buffer) p[i++] = 4; // (size of the data) p[i++] = handle; p[i++] = 0x00000000; // end tag p[0] = i*sizeof *p; // actual size mbox_property(file_desc, p); return p[5]; } uint32_t mem_lock(int file_desc, uint32_t handle) { int i=0; uint32_t p[32]; p[i++] = 0; // size p[i++] = 0x00000000; // process request p[i++] = 0x3000d; // (the tag id) p[i++] = 4; // (size of the buffer) p[i++] = 4; // (size of the data) p[i++] = handle; p[i++] = 0x00000000; // end tag p[0] = i*sizeof *p; // actual size if (mbox_property(file_desc, p) < 0) return ~0; else return p[5]; } uint32_t mem_unlock(int file_desc, uint32_t handle) { int i=0; uint32_t p[32]; p[i++] = 0; // size p[i++] = 0x00000000; // process request p[i++] = 0x3000e; // (the tag id) p[i++] = 4; // (size of the buffer) p[i++] = 4; // (size of the data) p[i++] = handle; p[i++] = 0x00000000; // end tag p[0] = i * sizeof(*p); // actual size mbox_property(file_desc, p); return p[5]; } uint32_t execute_code(int file_desc, uint32_t code, uint32_t r0, uint32_t r1, uint32_t r2, uint32_t r3, uint32_t r4, uint32_t r5) { int i=0; uint32_t p[32]; p[i++] = 0; // size p[i++] = 0x00000000; // process request p[i++] = 0x30010; // (the tag id) p[i++] = 28; // (size of the buffer) p[i++] = 28; // (size of the data) p[i++] = code; p[i++] = r0; p[i++] = r1; p[i++] = r2; p[i++] = r3; p[i++] = r4; p[i++] = r5; p[i++] = 0x00000000; // end tag p[0] = i * sizeof(*p); // actual size mbox_property(file_desc, p); return p[5]; } uint32_t qpu_enable(int file_desc, uint32_t enable) { int i=0; uint32_t p[32]; p[i++] = 0; // size p[i++] = 0x00000000; // process request p[i++] = 0x30012; // (the tag id) p[i++] = 4; // (size of the buffer) p[i++] = 4; // (size of the data) p[i++] = enable; p[i++] = 0x00000000; // end tag p[0] = i * sizeof(*p); // actual size mbox_property(file_desc, p); return p[5]; } uint32_t execute_qpu(int file_desc, uint32_t num_qpus, uint32_t control, uint32_t noflush, uint32_t timeout) { int i = 0; uint32_t p[32]; p[i++] = 0; // size p[i++] = 0x00000000; // process request p[i++] = 0x30011; // (the tag id) p[i++] = 16; // (size of the buffer) p[i++] = 16; // (size of the data) p[i++] = num_qpus; p[i++] = control; p[i++] = noflush; p[i++] = timeout; // ms p[i++] = 0x00000000; // end tag p[0] = i * sizeof(*p); // actual size mbox_property(file_desc, p); return p[5]; } int mbox_open(void) { int file_desc; char filename[64]; file_desc = open("/dev/vcio", 0); if (file_desc >= 0) { return file_desc; } // open a char device file used for communicating with kernel mbox driver sprintf(filename, "/tmp/mailbox-%d", getpid()); unlink(filename); if (mknod(filename, S_IFCHR|0600, makedev(100, 0)) < 0) { perror("Failed to create mailbox device\n"); return -1; } file_desc = open(filename, 0); if (file_desc < 0) { perror("Can't open device file\n"); unlink(filename); return -1; } unlink(filename); return file_desc; } void mbox_close(int file_desc) { close(file_desc); } ./library/legacy/rpi-ws281x/lib/linux.py0000664000175000017500000000536414223621661021207 0ustar jawn-smithjawn-smith# # linux.py # # Copyright (c) 2014 Jeremy Garff # # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted # provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of # conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, this list # of conditions and the following disclaimer in the documentation and/or other materials # provided with the distribution. # 3. Neither the name of the owner nor the names of its contributors may be used to endorse # or promote products derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT # OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # import SCons import string import array import os tools = ['gcc', 'g++', 'gnulink', 'ar', 'gas'] def linux_tools(env): for tool in tools: env.Tool(tool) if not env['V']: env['ARCOMSTR'] = 'AR ${TARGET}' env['ASCOMSTR'] = 'AS ${TARGET}' env['CCCOMSTR'] = 'CC ${TARGET}' env['CXXCOMSTR'] = 'C++ ${TARGET}' env['LINKCOMSTR'] = 'LINK ${TARGET}' env['RANLIBCOMSTR'] = 'RANLIB ${TARGET}' def linux_flags(env): env.MergeFlags({ 'CPPFLAGS' : ''' -g -O2 -Wall -Werror '''.split(), }), env.MergeFlags({ 'LINKFLAGS' : ''' '''.split() }) def linux_builders(env): env.Append(BUILDERS = { 'Program' : SCons.Builder.Builder( action = SCons.Action.Action('${LINK} -o ${TARGET} ${SOURCES} ${LINKFLAGS}', '${LINKCOMSTR}'), ), }) return 1 # The following are required functions by SCons when incorporating through tools def exists(env): return 1 def generate(env, **kwargs): [f(env) for f in (linux_tools, linux_flags, linux_builders)] ./library/legacy/rpi-ws281x/lib/rpihw.h0000664000175000017500000000373114223621661020774 0ustar jawn-smithjawn-smith/* * rpihw.h * * Copyright (c) 2014 Jeremy Garff * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * 3. Neither the name of the owner nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef __RPIHW_H__ #define __RPIHW_H__ typedef struct { uint32_t type; #define RPI_HWVER_TYPE_UNKNOWN 0 #define RPI_HWVER_TYPE_PI1 1 #define RPI_HWVER_TYPE_PI2 2 uint32_t hwver; uint32_t periph_base; uint32_t videocore_base; char *desc; } rpi_hw_t; const rpi_hw_t *rpi_hw_detect(void); #endif /* __RPIHW_H__ */ ./library/legacy/rpi-ws281x/lib/pwm.h0000664000175000017500000001052414223621661020444 0ustar jawn-smithjawn-smith/* * pwm.h * * Copyright (c) 2014 Jeremy Garff * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * 3. Neither the name of the owner nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef __PWM_H__ #define __PWM_H__ /* * * Pin mappint of alternate pin configuration for PWM * * GPIO ALT PWM0 ALT PWM1 * * 12 0 * 13 0 * 18 5 * 19 5 * 40 0 * 41 0 * 45 0 * 52 1 * 53 1 * */ #define RPI_PWM_CHANNELS 2 typedef struct { uint32_t ctl; #define RPI_PWM_CTL_MSEN2 (1 << 15) #define RPI_PWM_CTL_USEF2 (1 << 13) #define RPI_PWM_CTL_POLA2 (1 << 12) #define RPI_PWM_CTL_SBIT2 (1 << 11) #define RPI_PWM_CTL_RPTL2 (1 << 10) #define RPI_PWM_CTL_MODE2 (1 << 9) #define RPI_PWM_CTL_PWEN2 (1 << 8) #define RPI_PWM_CTL_MSEN1 (1 << 7) #define RPI_PWM_CTL_CLRF1 (1 << 6) #define RPI_PWM_CTL_USEF1 (1 << 5) #define RPI_PWM_CTL_POLA1 (1 << 4) #define RPI_PWM_CTL_SBIT1 (1 << 3) #define RPI_PWM_CTL_RPTL1 (1 << 2) #define RPI_PWM_CTL_MODE1 (1 << 1) #define RPI_PWM_CTL_PWEN1 (1 << 0) uint32_t sta; #define RPI_PWM_STA_STA4 (1 << 12) #define RPI_PWM_STA_STA3 (1 << 11) #define RPI_PWM_STA_STA2 (1 << 10) #define RPI_PWM_STA_STA1 (1 << 9) #define RPI_PWM_STA_BERR (1 << 8) #define RPI_PWM_STA_GAP04 (1 << 7) #define RPI_PWM_STA_GAP03 (1 << 6) #define RPI_PWM_STA_GAP02 (1 << 5) #define RPI_PWM_STA_GAP01 (1 << 4) #define RPI_PWM_STA_RERR1 (1 << 3) #define RPI_PWM_STA_WERR1 (1 << 2) #define RPI_PWM_STA_EMPT1 (1 << 1) #define RPI_PWM_STA_FULL1 (1 << 0) uint32_t dmac; #define RPI_PWM_DMAC_ENAB (1 << 31) #define RPI_PWM_DMAC_PANIC(val) ((val & 0xff) << 8) #define RPI_PWM_DMAC_DREQ(val) ((val & 0xff) << 0) uint32_t resvd_0x0c; uint32_t rng1; uint32_t dat1; uint32_t fif1; uint32_t resvd_0x1c; uint32_t rng2; uint32_t dat2; } __attribute__((packed)) pwm_t; #define PWM_OFFSET (0x0020c000) #define PWM_PERIPH_PHYS (0x7e20c000) typedef struct { int pinnum; int altnum; } pwm_pin_table_t; typedef struct { const int count; const pwm_pin_table_t *pins; } pwm_pin_tables_t; int pwm_pin_alt(int chan, int pinnum); #endif /* __PWM_H__ */ ./library/legacy/rpi-ws281x/lib/Makefile0000664000175000017500000000126614223621661021133 0ustar jawn-smithjawn-smith.PHONY: clean lib all: lib test lib: libws2811.a ws2811.o: gcc -o ws2811.o -c -g -O2 -Wall -Werror ws2811.c -fPIC rpihw.o: gcc -o rpihw.o -c -g -O2 -Wall -Werror rpihw.c -fPIC pwm.o: gcc -o pwm.o -c -g -O2 -Wall -Werror pwm.c -fPIC dma.o: gcc -o dma.o -c -g -O2 -Wall -Werror dma.c -fPIC mailbox.o: gcc -o mailbox.o -c -g -O2 -Wall -Werror mailbox.c -fPIC libws2811.a: ws2811.o rpihw.o pwm.o dma.o mailbox.o ar rc libws2811.a ws2811.o rpihw.o pwm.o dma.o mailbox.o ranlib libws2811.a main.o: gcc -o main.o -c -g -O2 -Wall -Werror main.c test: main.o libws2811.a gcc -o test main.o libws2811.a clean: -rm -f ws2811.o rpihw.o pwm.o dma.o mailbox.o libws2811.a main.o test ./library/legacy/rpi-ws281x/lib/main.c0000664000175000017500000001050514223621661020557 0ustar jawn-smithjawn-smith/* * main.c * * Copyright (c) 2014 Jeremy Garff * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * 3. Neither the name of the owner nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include #include #include #include #include #include #include #include #include #include #include "clk.h" #include "gpio.h" #include "dma.h" #include "pwm.h" #include "ws2811.h" #define ARRAY_SIZE(stuff) (sizeof(stuff) / sizeof(stuff[0])) #define TARGET_FREQ WS2811_TARGET_FREQ #define GPIO_PIN 18 #define DMA 5 #define WIDTH 8 #define HEIGHT 8 #define LED_COUNT (WIDTH * HEIGHT) ws2811_t ledstring = { .freq = TARGET_FREQ, .dmanum = DMA, .channel = { [0] = { .gpionum = GPIO_PIN, .count = LED_COUNT, .invert = 0, .brightness = 255, }, [1] = { .gpionum = 0, .count = 0, .invert = 0, .brightness = 0, }, }, }; ws2811_led_t matrix[WIDTH][HEIGHT]; void matrix_render(void) { int x, y; for (x = 0; x < WIDTH; x++) { for (y = 0; y < HEIGHT; y++) { ledstring.channel[0].leds[(y * WIDTH) + x] = matrix[x][y]; } } } void matrix_raise(void) { int x, y; for (y = 0; y < (HEIGHT - 1); y++) { for (x = 0; x < WIDTH; x++) { matrix[x][y] = matrix[x][y + 1]; } } } int dotspos[] = { 0, 1, 2, 3, 4, 5, 6, 7 }; ws2811_led_t dotcolors[] = { 0x200000, // red 0x201000, // orange 0x202000, // yellow 0x002000, // green 0x002020, // lightblue 0x000020, // blue 0x100010, // purple 0x200010, // pink }; void matrix_bottom(void) { int i; for (i = 0; i < ARRAY_SIZE(dotspos); i++) { dotspos[i]++; if (dotspos[i] > (WIDTH - 1)) { dotspos[i] = 0; } matrix[dotspos[i]][HEIGHT - 1] = dotcolors[i]; } } static void ctrl_c_handler(int signum) { ws2811_fini(&ledstring); } static void setup_handlers(void) { struct sigaction sa = { .sa_handler = ctrl_c_handler, }; sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); } int main(int argc, char *argv[]) { int ret = 0; setup_handlers(); if (ws2811_init(&ledstring)) { return -1; } while (1) { matrix_raise(); matrix_bottom(); matrix_render(); if (ws2811_render(&ledstring)) { ret = -1; break; } // 15 frames /sec usleep(1000000 / 15); } ws2811_fini(&ledstring); return ret; } ./library/legacy/rpi-ws281x/lib/mailbox.h0000664000175000017500000000445514223621661021302 0ustar jawn-smithjawn-smith/* Copyright (c) 2012, Broadcom Europe Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #define MAJOR_NUM 100 #define IOCTL_MBOX_PROPERTY _IOWR(MAJOR_NUM, 0, char *) int mbox_open(void); void mbox_close(int file_desc); unsigned get_version(int file_desc); unsigned mem_alloc(int file_desc, unsigned size, unsigned align, unsigned flags); unsigned mem_free(int file_desc, unsigned handle); unsigned mem_lock(int file_desc, unsigned handle); unsigned mem_unlock(int file_desc, unsigned handle); void *mapmem(unsigned base, unsigned size); void *unmapmem(void *addr, unsigned size); unsigned execute_code(int file_desc, unsigned code, unsigned r0, unsigned r1, unsigned r2, unsigned r3, unsigned r4, unsigned r5); unsigned execute_qpu(int file_desc, unsigned num_qpus, unsigned control, unsigned noflush, unsigned timeout); unsigned qpu_enable(int file_desc, unsigned enable); ./library/legacy/rpi-ws281x/lib/gamma.h0000664000175000017500000000202214223621661020715 0ustar jawn-smithjawn-smith#ifndef GAMMA_H #define GAMMA_H const uint8_t ws281x_gamma[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 21, 21, 22, 22, 23, 23, 24, 25, 25, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33, 34, 34, 35, 36, 37, 37, 38, 39, 40, 40, 41, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 76, 77, 78, 79, 80, 81, 83, 84, 85, 86, 88, 89, 90, 91, 93, 94, 95, 96, 98, 99,100,102,103,104,106,107,109,110, 111,113,114,116,117,119,120,121,123,124,126,128,129,131,132,134, 135,137,138,140,142,143,145,146,148,150,151,153,155,157,158,160, 162,163,165,167,169,170,172,174,176,178,179,181,183,185,187,189, 191,193,194,196,198,200,202,204,206,208,210,212,214,216,218,220, 222,224,227,229,231,233,235,237,239,241,244,246,248,250,252,255}; #endif ./library/legacy/rpi-ws281x/lib/LICENSE0000664000175000017500000000241214223621661020472 0ustar jawn-smithjawn-smithCopyright (c) 2014, jgarff All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ./library/legacy/rpi-ws281x/lib/ws2811.h0000664000175000017500000000705014223621661020606 0ustar jawn-smithjawn-smith/* * ws2811.h * * Copyright (c) 2014 Jeremy Garff * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * 3. Neither the name of the owner nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef __WS2811_H__ #define __WS2811_H__ #ifdef __cplusplus extern "C" { #endif #include "rpihw.h" #include "pwm.h" #define WS2811_TARGET_FREQ 800000 // Can go as low as 400000 #define WS2811_STRIP_RGB 0x100800 #define WS2811_STRIP_RBG 0x100008 #define WS2811_STRIP_GRB 0x081000 #define WS2811_STRIP_GBR 0x080010 #define WS2811_STRIP_BRG 0x001008 #define WS2811_STRIP_BGR 0x000810 struct ws2811_device; typedef uint32_t ws2811_led_t; //< 0x00RRGGBB typedef struct { int gpionum; //< GPIO Pin with PWM alternate function, 0 if unused int invert; //< Invert output signal int count; //< Number of LEDs, 0 if channel is unused int brightness; //< Brightness value between 0 and 255 int strip_type; //< Strip color layout -- one of WS2811_STRIP_xxx constants ws2811_led_t *leds; //< LED buffers, allocated by driver based on count } ws2811_channel_t; typedef struct { struct ws2811_device *device; //< Private data for driver use const rpi_hw_t *rpi_hw; //< RPI Hardware Information uint32_t freq; //< Required output frequency int dmanum; //< DMA number _not_ already in use ws2811_channel_t channel[RPI_PWM_CHANNELS]; } ws2811_t; int ws2811_init(ws2811_t *ws2811); //< Initialize buffers/hardware void ws2811_fini(ws2811_t *ws2811); //< Tear it all down int ws2811_render(ws2811_t *ws2811); //< Send LEDs off to hardware int ws2811_wait(ws2811_t *ws2811); //< Wait for DMA completion #ifdef __cplusplus } #endif #endif /* __WS2811_H__ */ ./library/legacy/rpi-ws281x/lib/dma.c0000664000175000017500000000447214223621661020402 0ustar jawn-smithjawn-smith/* * dma.c * * Copyright (c) 2014 Jeremy Garff * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * 3. Neither the name of the owner nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include #include #include #include #include #include #include #include #include "dma.h" // DMA address mapping by DMA number index static const uint32_t dma_offset[] = { DMA0_OFFSET, DMA1_OFFSET, DMA2_OFFSET, DMA3_OFFSET, DMA4_OFFSET, DMA5_OFFSET, DMA6_OFFSET, DMA7_OFFSET, DMA8_OFFSET, DMA9_OFFSET, DMA10_OFFSET, DMA11_OFFSET, DMA12_OFFSET, DMA13_OFFSET, DMA14_OFFSET, DMA15_OFFSET, }; uint32_t dmanum_to_offset(int dmanum) { int array_size = sizeof(dma_offset) / sizeof(dma_offset[0]); if (dmanum >= array_size) { return 0; } return dma_offset[dmanum]; } ./library/legacy/rpi-ws281x/lib/rpihw.c0000664000175000017500000002070514223621661020767 0ustar jawn-smithjawn-smith/* * rpihw.c * * Copyright (c) 2014 Jeremy Garff * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * 3. Neither the name of the owner nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include #include #include #include #include #include "rpihw.h" #define LINE_WIDTH_MAX 80 #define HW_VER_STRING "Revision" #define PERIPH_BASE_RPI 0x20000000 #define PERIPH_BASE_RPI2 0x3f000000 #define VIDEOCORE_BASE_RPI 0x40000000 #define VIDEOCORE_BASE_RPI2 0xc0000000 static const rpi_hw_t rpi_hw_info[] = { // // Model B Rev 1.0 // { .hwver = 0x02, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Model B", }, { .hwver = 0x03, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Model B", }, // // Model B Rev 2.0 // { .hwver = 0x04, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Model B", }, { .hwver = 0x05, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Model B", }, { .hwver = 0x06, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Model B", }, // // Model A // { .hwver = 0x07, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Model A", }, { .hwver = 0x08, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Model A", }, { .hwver = 0x09, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Model A", }, // // Model B // { .hwver = 0x0d, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Model B", }, { .hwver = 0x0e, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Model B", }, { .hwver = 0x0f, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Model B", }, // // Model B+ // { .hwver = 0x10, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Model B+", }, { .hwver = 0x13, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Model B+", }, // // Compute Module // { .hwver = 0x11, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Compute Module", }, { .hwver = 0x14, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Compute Module", }, // // Pi Zero // { .hwver = 0x900092, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Pi Zero v1.2", }, { .hwver = 0x900093, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Pi Zero v1.3", }, { .hwver = 0x920093, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Pi Zero v1.3", }, { .hwver = 0x9000c1, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Pi Zero W v1.1", }, // // Model A+ // { .hwver = 0x12, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Model A+", }, { .hwver = 0x15, .type = RPI_HWVER_TYPE_PI1, .periph_base = PERIPH_BASE_RPI, .videocore_base = VIDEOCORE_BASE_RPI, .desc = "Model A+", }, // // Pi 2 Model B // { .hwver = 0xa01040, // Les Pounder is a special little snowflake edition ;) .type = RPI_HWVER_TYPE_PI2, .periph_base = PERIPH_BASE_RPI2, .videocore_base = VIDEOCORE_BASE_RPI2, .desc = "Pi 2", }, { .hwver = 0xa01041, .type = RPI_HWVER_TYPE_PI2, .periph_base = PERIPH_BASE_RPI2, .videocore_base = VIDEOCORE_BASE_RPI2, .desc = "Pi 2", }, { .hwver = 0xa21041, .type = RPI_HWVER_TYPE_PI2, .periph_base = PERIPH_BASE_RPI2, .videocore_base = VIDEOCORE_BASE_RPI2, .desc = "Pi 2", }, // // Pi 2 with BCM2837 // { .hwver = 0xa22042, .type = RPI_HWVER_TYPE_PI2, .periph_base = PERIPH_BASE_RPI2, .videocore_base = VIDEOCORE_BASE_RPI2, .desc = "Pi 2", }, // // Pi 3 Model B // { .hwver = 0xa02082, .type = RPI_HWVER_TYPE_PI2, .periph_base = PERIPH_BASE_RPI2, .videocore_base = VIDEOCORE_BASE_RPI2, .desc = "Pi 3", }, { .hwver = 0xa22082, .type = RPI_HWVER_TYPE_PI2, .periph_base = PERIPH_BASE_RPI2, .videocore_base = VIDEOCORE_BASE_RPI2, .desc = "Pi 3", }, }; const rpi_hw_t *rpi_hw_detect(void) { FILE *f = fopen("/proc/cpuinfo", "r"); char line[LINE_WIDTH_MAX]; const rpi_hw_t *result = NULL; if (!f) { return NULL; } while (fgets(line, LINE_WIDTH_MAX - 1, f)) { if (strstr(line, HW_VER_STRING)) { uint32_t rev; char *substr; unsigned i; substr = strstr(line, ": "); if (!substr) { continue; } errno = 0; rev = strtoul(&substr[1], NULL, 16); // Base 16 if (errno) { continue; } for (i = 0; i < (sizeof(rpi_hw_info) / sizeof(rpi_hw_info[0])); i++) { if (rev == rpi_hw_info[i].hwver) { result = &rpi_hw_info[i]; goto done; } } } } done: fclose(f); return result; } ./library/legacy/rpi-ws281x/lib/pwm.c0000664000175000017500000000563014223621661020441 0ustar jawn-smithjawn-smith/* * pwm.c * * Copyright (c) 2014 Jeremy Garff * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * 3. Neither the name of the owner nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include #include "ws2811.h" #include "pwm.h" // Mapping of Pin to alternate function for PWM channel 0 const pwm_pin_table_t pwm_pin_chan0[] = { { .pinnum = 12, .altnum = 0, }, { .pinnum = 18, .altnum = 5, }, { .pinnum = 40, .altnum = 0, }, { .pinnum = 52, .altnum = 1, }, }; // Mapping of Pin to alternate function for PWM channel 1 const pwm_pin_table_t pwm_pin_chan1[] = { { .pinnum = 13, .altnum = 0, }, { .pinnum = 19, .altnum = 5, }, { .pinnum = 41, .altnum = 0, }, { .pinnum = 45, .altnum = 0, }, { .pinnum = 53, .altnum = 1, }, }; const pwm_pin_tables_t pwm_pin_tables[RPI_PWM_CHANNELS] = { { .pins = pwm_pin_chan0, .count = sizeof(pwm_pin_chan0) / sizeof(pwm_pin_chan0[0]), }, { .pins = pwm_pin_chan1, .count = sizeof(pwm_pin_chan1) / sizeof(pwm_pin_chan1[0]), }, }; int pwm_pin_alt(int chan, int pinnum) { const pwm_pin_tables_t *pintable = &pwm_pin_tables[chan]; int i; for (i = 0; i < pintable->count; i++) { if (pintable->pins[i].pinnum == pinnum) { return pintable->pins[i].altnum; } } return -1; } ./library/legacy/rpi-ws281x/lib/gpio.h0000664000175000017500000001006114223621661020573 0ustar jawn-smithjawn-smith/* * gpio.h * * Copyright (c) 2014 Jeremy Garff * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * 3. Neither the name of the owner nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef __GPIO_H__ #define __GPIO_H__ typedef struct { uint32_t fsel[6]; // GPIO Function Select uint32_t resvd_0x18; uint32_t set[2]; // GPIO Pin Output Set uint32_t resvd_0x24; uint32_t clr[2]; // GPIO Pin Output Clear uint32_t resvd_0x30; uint32_t lev[2]; // GPIO Pin Level uint32_t resvd_0x3c; uint32_t eds[2]; // GPIO Pin Event Detect Status uint32_t resvd_0x48; uint32_t ren[2]; // GPIO Pin Rising Edge Detect Enable uint32_t resvd_0x54; uint32_t fen[2]; // GPIO Pin Falling Edge Detect Enable uint32_t resvd_0x60; uint32_t hen[2]; // GPIO Pin High Detect Enable uint32_t resvd_0x6c; uint32_t len[2]; // GPIO Pin Low Detect Enable uint32_t resvd_0x78; uint32_t aren[2]; // GPIO Pin Async Rising Edge Detect uint32_t resvd_0x84; uint32_t afen[2]; // GPIO Pin Async Falling Edge Detect uint32_t resvd_0x90; uint32_t pud; // GPIO Pin Pull up/down Enable uint32_t pudclk[2]; // GPIO Pin Pull up/down Enable Clock uint32_t resvd_0xa0[4]; uint32_t test; } __attribute__((packed)) gpio_t; #define GPIO_OFFSET (0x00200000) static inline void gpio_function_set(volatile gpio_t *gpio, uint8_t pin, uint8_t function) { int regnum = pin / 10; int offset = (pin % 10) * 3; uint8_t funcmap[] = { 4, 5, 6, 7, 3, 2 }; // See datasheet for mapping if (function > 5) { return; } gpio->fsel[regnum] &= ~(0x7 << offset); gpio->fsel[regnum] |= ((funcmap[function]) << offset); } static inline void gpio_level_set(volatile gpio_t *gpio, uint8_t pin, uint8_t level) { int regnum = pin >> 5; int offset = (pin & 0x1f); if (level) { gpio->set[regnum] = (1 << offset); } else { gpio->clr[regnum] = (1 << offset); } } static inline void gpio_output_set(volatile gpio_t *gpio, uint8_t pin, uint8_t output) { int regnum = pin / 10; int offset = (pin % 10) * 3; uint8_t function = output ? 1 : 0; // See datasheet for mapping gpio->fsel[regnum] &= ~(0x7 << offset); gpio->fsel[regnum] |= ((function & 0x7) << offset); } #endif /* __GPIO_H__ */ ./library/legacy/rpi-ws281x/rpi_ws281x.i0000664000175000017500000000226614223621661021026 0ustar jawn-smithjawn-smith// SWIG interface file to define rpi_ws281x library python wrapper. // Author: Tony DiCola (tony@tonydicola.com), Jeremy Garff (jer@jers.net) // Define module name rpi_ws281x. This will actually be imported under // the name _rpi_ws281x following the SWIG & Python conventions. %module rpi_ws281x // Include standard SWIG types & array support for support of uint32_t // parameters and arrays. %include "stdint.i" %include "carrays.i" // Declare functions which will be exported as anything in the ws2811.h header. %{ #include "lib/ws2811.h" %} // Process ws2811.h header and export all included functions. %include "lib/ws2811.h" %inline %{ uint32_t ws2811_led_get(ws2811_channel_t *channel, int lednum) { if (lednum >= channel->count) { return -1; } return channel->leds[lednum]; } int ws2811_led_set(ws2811_channel_t *channel, int lednum, uint32_t color) { if (lednum >= channel->count) { return -1; } channel->leds[lednum] = color; return 0; } ws2811_channel_t *ws2811_channel_get(ws2811_t *ws, int channelnum) { return &ws->channel[channelnum]; } %} ./library/legacy/rpi-ws281x/neopixel.py0000664000175000017500000001322314223621661021116 0ustar jawn-smithjawn-smith# Adafruit NeoPixel library port to the rpi_ws281x library. # Author: Tony DiCola (tony@tonydicola.com), Jeremy Garff (jer@jers.net) import _rpi_ws281x as ws import atexit def Color(red, green, blue): """Convert the provided red, green, blue color to a 24-bit color value. Each color component should be a value 0-255 where 0 is the lowest intensity and 255 is the highest intensity. """ return (red << 16) | (green << 8) | blue class _LED_Data(object): """Wrapper class which makes a SWIG LED color data array look and feel like a Python list of integers. """ def __init__(self, channel, size): self.size = size self.channel = channel def __getitem__(self, pos): """Return the 24-bit RGB color value at the provided position or slice of positions. """ # Handle if a slice of positions are passed in by grabbing all the values # and returning them in a list. if isinstance(pos, slice): return [ws.ws2811_led_get(self.channel, n) for n in range(pos.indices(self.size))] # Else assume the passed in value is a number to the position. else: return ws.ws2811_led_get(self.channel, pos) def __setitem__(self, pos, value): """Set the 24-bit RGB color value at the provided position or slice of positions. """ # Handle if a slice of positions are passed in by setting the appropriate # LED data values to the provided values. if isinstance(pos, slice): index = 0 for n in range(pos.indices(self.size)): ws.ws2811_led_set(self.channel, n, value[index]) index += 1 # Else assume the passed in value is a number to the position. else: return ws.ws2811_led_set(self.channel, pos, value) class Adafruit_NeoPixel(object): def __init__(self, num, pin, freq_hz=800000, dma=5, invert=False, brightness=128, channel=0): """Class to represent a NeoPixel/WS281x LED display. Num should be the number of pixels in the display, and pin should be the GPIO pin connected to the display signal line (must be a PWM pin like 18!). Optional parameters are freq, the frequency of the display signal in hertz (default 800khz), dma, the DMA channel to use (default 5), invert, a boolean specifying if the signal line should be inverted (default False), and channel, the PWM channel to use (defaults to 0). """ # Create ws2811_t structure and fill in parameters. self._leds = ws.new_ws2811_t() # Initialize the channels to zero for channum in range(2): chan = ws.ws2811_channel_get(self._leds, channum) ws.ws2811_channel_t_count_set(chan, 0) ws.ws2811_channel_t_gpionum_set(chan, 0) ws.ws2811_channel_t_invert_set(chan, 0) ws.ws2811_channel_t_brightness_set(chan, 0) # Initialize the channel in use self._channel = ws.ws2811_channel_get(self._leds, channel) ws.ws2811_channel_t_count_set(self._channel, num) ws.ws2811_channel_t_gpionum_set(self._channel, pin) ws.ws2811_channel_t_invert_set(self._channel, 0 if not invert else 1) ws.ws2811_channel_t_brightness_set(self._channel, brightness) ws.ws2811_channel_t_strip_type_set(self._channel, ws.WS2811_STRIP_GRB) # Initialize the controller ws.ws2811_t_freq_set(self._leds, freq_hz) ws.ws2811_t_dmanum_set(self._leds, dma) # Grab the led data array. self._led_data = _LED_Data(self._channel, num) # Substitute for __del__, traps an exit condition and cleans up properly atexit.register(self._cleanup) def __del__(self): # Required because Python will complain about memory leaks # However there's no guarantee that "ws" will even be set # when the __del__ method for this class is reached. if ws != None: self._cleanup() def _cleanup(self): # Clean up memory used by the library when not needed anymore. if self._leds is not None: print("Exiting cleanly") ws.ws2811_fini(self._leds) ws.delete_ws2811_t(self._leds) self._leds = None self._channel = None # Note that ws2811_fini will free the memory used by led_data internally. def begin(self): """Initialize library, must be called once before other functions are called. """ resp = ws.ws2811_init(self._leds) if resp != 0: raise RuntimeError('ws2811_init failed with code {0}'.format(resp)) def show(self): """Update the display with the data from the LED buffer.""" resp = ws.ws2811_render(self._leds) if resp != 0: raise RuntimeError('ws2811_render failed with code {0}'.format(resp)) def setPixelColor(self, n, color): """Set LED at position n to the provided 24-bit color value (in RGB order). """ self._led_data[n] = color def setPixelColorRGB(self, n, red, green, blue): """Set LED at position n to the provided red, green, and blue color. Each color component should be a value from 0 to 255 (where 0 is the lowest intensity and 255 is the highest intensity). """ self.setPixelColor(n, Color(red, green, blue)) def getBrightness(self): return ws.ws2811_channel_t_brightness_get(self._channel) def setBrightness(self, brightness): """Scale each LED in the buffer by the provided brightness. A brightness of 0 is the darkest and 255 is the brightest. """ ws.ws2811_channel_t_brightness_set(self._channel, brightness) def getPixels(self): """Return an object which allows access to the LED display data as if it were a sequence of 24-bit RGB values. """ return self._led_data def numPixels(self): """Return the number of pixels in the display.""" return ws.ws2811_channel_t_count_get(self._channel) def getPixelColor(self, n): """Get the 24-bit RGB color value for the LED at position n.""" return self._led_data[n] def getPixelColorRGB(self, n): c = lambda: None setattr(c, 'r', self._led_data[n] >> 16 & 0xff) setattr(c, 'g', self._led_data[n] >> 8 & 0xff) setattr(c, 'b', self._led_data[n] & 0xff) return c ./library/legacy/rpi-ws281x/README.md0000664000175000017500000000514014223621661020177 0ustar jawn-smithjawn-smithrpi_ws281x ========== Originally from: https://github.com/jgarff/rpi_ws281x Thanks to Richard Hirst for Pi 2 compatible code: https://github.com/richardghirst/rpi_ws281x ##Userspace Raspberry Pi PWM library for WS281X LEDs ###Background: The BCM2835 in the Raspberry Pi has a PWM module that is well suited to driving individually controllable WS281X LEDs. Using the DMA, PWM FIFO, and serial mode in the PWM, it's possible to control almost any number of WS281X LEDs in a chain connected to the PWM output pin. This library and test program set the clock rate of the PWM controller to 3X the desired output frequency and creates a bit pattern in RAM from an array of colors where each bit is represented by 3 bits for the PWM controller as follows. Bit 1 - 1 1 0 Bit 0 - 1 0 0 ###Hardware: WS281X LEDs are generally driven at 5V, which requires that the data signal be at the same level. Converting the output from a Raspberry Pi GPIO/PWM to a higher voltage through a level shifter is required. It is possible to run the LEDs from a 3.3V - 3.6V power source, and connect the GPIO directly at a cost of brightness, but this isn't recommended. The test program is designed to drive a 8x8 grid of LEDs from Adafruit (http://www.adafruit.com/products/1487). Please see the Adafruit website for more information. Know what you're doing with the hardware and electricity. I take no reponsibility for damage, harm, or mistakes. ###Build: - Install Scons (on raspbian, apt-get install scons). - Make sure to adjust the parameters in main.c to suit your hardare. - Signal rate (400kHz to 800kHz). Default 800kHz. - ledstring.invert=1 if using a inverting level shifter. - Width and height of LED matrix (height=1 for LED string). - Type 'scons' from inside the source directory. ###Running: - Type 'sudo scons'. - Type 'sudo ./test'. - That's it. You should see a moving rainbow scroll across the display. ###Usage: The API is very simple. Make sure to create and initialize the ws2811_t structure as seen in main.c. From there it can be initialized by calling ws2811_init(). LEDs are changed by modifying the color in the .led[index] array and calling ws2811_render(). The rest is handled by the library, which creates the DMA memory and starts the DMA/PWM. Make sure to hook a signal handler for SIGKILL to do cleanup. From the handler make sure to call ws2811_fini(). It'll make sure that the DMA is finished before program execution stops. That's it. Have fun. This was a fun little weekend project. I hope you find it useful. I plan to add some diagrams, waveform scope shots, and a .deb package soon. ./library/legacy/rpi-ws281x/rpi_ws281x.py0000664000175000017500000001640714223621661021230 0ustar jawn-smithjawn-smith# 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('_rpi_ws281x', [dirname(__file__)]) except ImportError: import _rpi_ws281x return _rpi_ws281x if fp is not None: try: _mod = imp.load_module('_rpi_ws281x', fp, pathname, description) finally: fp.close() return _mod _rpi_ws281x = swig_import_helper() del swig_import_helper else: import _rpi_ws281x 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 WS2811_TARGET_FREQ = _rpi_ws281x.WS2811_TARGET_FREQ WS2811_STRIP_RGB = _rpi_ws281x.WS2811_STRIP_RGB WS2811_STRIP_RBG = _rpi_ws281x.WS2811_STRIP_RBG WS2811_STRIP_GRB = _rpi_ws281x.WS2811_STRIP_GRB WS2811_STRIP_GBR = _rpi_ws281x.WS2811_STRIP_GBR WS2811_STRIP_BRG = _rpi_ws281x.WS2811_STRIP_BRG WS2811_STRIP_BGR = _rpi_ws281x.WS2811_STRIP_BGR class ws2811_channel_t(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, ws2811_channel_t, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, ws2811_channel_t, name) __repr__ = _swig_repr __swig_setmethods__["gpionum"] = _rpi_ws281x.ws2811_channel_t_gpionum_set __swig_getmethods__["gpionum"] = _rpi_ws281x.ws2811_channel_t_gpionum_get if _newclass:gpionum = _swig_property(_rpi_ws281x.ws2811_channel_t_gpionum_get, _rpi_ws281x.ws2811_channel_t_gpionum_set) __swig_setmethods__["invert"] = _rpi_ws281x.ws2811_channel_t_invert_set __swig_getmethods__["invert"] = _rpi_ws281x.ws2811_channel_t_invert_get if _newclass:invert = _swig_property(_rpi_ws281x.ws2811_channel_t_invert_get, _rpi_ws281x.ws2811_channel_t_invert_set) __swig_setmethods__["count"] = _rpi_ws281x.ws2811_channel_t_count_set __swig_getmethods__["count"] = _rpi_ws281x.ws2811_channel_t_count_get if _newclass:count = _swig_property(_rpi_ws281x.ws2811_channel_t_count_get, _rpi_ws281x.ws2811_channel_t_count_set) __swig_setmethods__["brightness"] = _rpi_ws281x.ws2811_channel_t_brightness_set __swig_getmethods__["brightness"] = _rpi_ws281x.ws2811_channel_t_brightness_get if _newclass:brightness = _swig_property(_rpi_ws281x.ws2811_channel_t_brightness_get, _rpi_ws281x.ws2811_channel_t_brightness_set) __swig_setmethods__["strip_type"] = _rpi_ws281x.ws2811_channel_t_strip_type_set __swig_getmethods__["strip_type"] = _rpi_ws281x.ws2811_channel_t_strip_type_get if _newclass:strip_type = _swig_property(_rpi_ws281x.ws2811_channel_t_strip_type_get, _rpi_ws281x.ws2811_channel_t_strip_type_set) __swig_setmethods__["leds"] = _rpi_ws281x.ws2811_channel_t_leds_set __swig_getmethods__["leds"] = _rpi_ws281x.ws2811_channel_t_leds_get if _newclass:leds = _swig_property(_rpi_ws281x.ws2811_channel_t_leds_get, _rpi_ws281x.ws2811_channel_t_leds_set) def __init__(self): this = _rpi_ws281x.new_ws2811_channel_t() try: self.this.append(this) except: self.this = this __swig_destroy__ = _rpi_ws281x.delete_ws2811_channel_t __del__ = lambda self : None; ws2811_channel_t_swigregister = _rpi_ws281x.ws2811_channel_t_swigregister ws2811_channel_t_swigregister(ws2811_channel_t) class ws2811_t(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, ws2811_t, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, ws2811_t, name) __repr__ = _swig_repr __swig_setmethods__["device"] = _rpi_ws281x.ws2811_t_device_set __swig_getmethods__["device"] = _rpi_ws281x.ws2811_t_device_get if _newclass:device = _swig_property(_rpi_ws281x.ws2811_t_device_get, _rpi_ws281x.ws2811_t_device_set) __swig_setmethods__["rpi_hw"] = _rpi_ws281x.ws2811_t_rpi_hw_set __swig_getmethods__["rpi_hw"] = _rpi_ws281x.ws2811_t_rpi_hw_get if _newclass:rpi_hw = _swig_property(_rpi_ws281x.ws2811_t_rpi_hw_get, _rpi_ws281x.ws2811_t_rpi_hw_set) __swig_setmethods__["freq"] = _rpi_ws281x.ws2811_t_freq_set __swig_getmethods__["freq"] = _rpi_ws281x.ws2811_t_freq_get if _newclass:freq = _swig_property(_rpi_ws281x.ws2811_t_freq_get, _rpi_ws281x.ws2811_t_freq_set) __swig_setmethods__["dmanum"] = _rpi_ws281x.ws2811_t_dmanum_set __swig_getmethods__["dmanum"] = _rpi_ws281x.ws2811_t_dmanum_get if _newclass:dmanum = _swig_property(_rpi_ws281x.ws2811_t_dmanum_get, _rpi_ws281x.ws2811_t_dmanum_set) __swig_setmethods__["channel"] = _rpi_ws281x.ws2811_t_channel_set __swig_getmethods__["channel"] = _rpi_ws281x.ws2811_t_channel_get if _newclass:channel = _swig_property(_rpi_ws281x.ws2811_t_channel_get, _rpi_ws281x.ws2811_t_channel_set) def __init__(self): this = _rpi_ws281x.new_ws2811_t() try: self.this.append(this) except: self.this = this __swig_destroy__ = _rpi_ws281x.delete_ws2811_t __del__ = lambda self : None; ws2811_t_swigregister = _rpi_ws281x.ws2811_t_swigregister ws2811_t_swigregister(ws2811_t) def ws2811_init(*args): return _rpi_ws281x.ws2811_init(*args) ws2811_init = _rpi_ws281x.ws2811_init def ws2811_fini(*args): return _rpi_ws281x.ws2811_fini(*args) ws2811_fini = _rpi_ws281x.ws2811_fini def ws2811_render(*args): return _rpi_ws281x.ws2811_render(*args) ws2811_render = _rpi_ws281x.ws2811_render def ws2811_wait(*args): return _rpi_ws281x.ws2811_wait(*args) ws2811_wait = _rpi_ws281x.ws2811_wait def ws2811_led_get(*args): return _rpi_ws281x.ws2811_led_get(*args) ws2811_led_get = _rpi_ws281x.ws2811_led_get def ws2811_led_set(*args): return _rpi_ws281x.ws2811_led_set(*args) ws2811_led_set = _rpi_ws281x.ws2811_led_set def ws2811_channel_get(*args): return _rpi_ws281x.ws2811_channel_get(*args) ws2811_channel_get = _rpi_ws281x.ws2811_channel_get # This file is compatible with both classic and new-style classes. ./library/legacy/rpi-ws281x/rpi_ws281x_wrap.c0000664000175000017500000044563314223621661022062 0ustar jawn-smithjawn-smith/* ---------------------------------------------------------------------------- * 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_rpi_hw_t swig_types[3] #define SWIGTYPE_p_short swig_types[4] #define SWIGTYPE_p_signed_char swig_types[5] #define SWIGTYPE_p_unsigned_char swig_types[6] #define SWIGTYPE_p_unsigned_int swig_types[7] #define SWIGTYPE_p_unsigned_long_long swig_types[8] #define SWIGTYPE_p_unsigned_short swig_types[9] #define SWIGTYPE_p_ws2811_channel_t swig_types[10] #define SWIGTYPE_p_ws2811_device swig_types[11] #define SWIGTYPE_p_ws2811_t swig_types[12] static swig_type_info *swig_types[14]; static swig_module_info swig_module = {swig_types, 13, 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):= _rpi_ws281x.so ------------------------------------------------*/ #if PY_VERSION_HEX >= 0x03000000 # define SWIG_init PyInit__rpi_ws281x #else # define SWIG_init init_rpi_ws281x #endif #define SWIG_name "_rpi_ws281x" #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/ws2811.h" SWIGINTERNINLINE PyObject* SWIG_From_int (int value) { return PyInt_FromLong((long) value); } #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_long (PyObject *obj, long* val) { if (PyInt_Check(obj)) { if (val) *val = PyInt_AsLong(obj); return SWIG_OK; } else if (PyLong_Check(obj)) { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } #ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; long v = PyInt_AsLong(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, LONG_MIN, LONG_MAX)) { if (val) *val = (long)(d); return res; } } } #endif return SWIG_TypeError; } SWIGINTERN int SWIG_AsVal_int (PyObject * obj, int *val) { long v; int res = SWIG_AsVal_long (obj, &v); if (SWIG_IsOK(res)) { if ((v < INT_MIN || v > INT_MAX)) { return SWIG_OverflowError; } else { if (val) *val = (int)(v); } } return res; } 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_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); } uint32_t ws2811_led_get(ws2811_channel_t *channel, int lednum) { if (lednum >= channel->count) { return -1; } return channel->leds[lednum]; } int ws2811_led_set(ws2811_channel_t *channel, int lednum, uint32_t color) { if (lednum >= channel->count) { return -1; } channel->leds[lednum] = color; return 0; } ws2811_channel_t *ws2811_channel_get(ws2811_t *ws, int channelnum) { return &ws->channel[channelnum]; } #ifdef __cplusplus extern "C" { #endif SWIGINTERN PyObject *_wrap_ws2811_channel_t_gpionum_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_channel_t *arg1 = (ws2811_channel_t *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:ws2811_channel_t_gpionum_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_channel_t_gpionum_set" "', argument " "1"" of type '" "ws2811_channel_t *""'"); } arg1 = (ws2811_channel_t *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "ws2811_channel_t_gpionum_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->gpionum = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_channel_t_gpionum_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_channel_t *arg1 = (ws2811_channel_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:ws2811_channel_t_gpionum_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_channel_t_gpionum_get" "', argument " "1"" of type '" "ws2811_channel_t *""'"); } arg1 = (ws2811_channel_t *)(argp1); result = (int) ((arg1)->gpionum); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_channel_t_invert_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_channel_t *arg1 = (ws2811_channel_t *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:ws2811_channel_t_invert_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_channel_t_invert_set" "', argument " "1"" of type '" "ws2811_channel_t *""'"); } arg1 = (ws2811_channel_t *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "ws2811_channel_t_invert_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->invert = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_channel_t_invert_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_channel_t *arg1 = (ws2811_channel_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:ws2811_channel_t_invert_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_channel_t_invert_get" "', argument " "1"" of type '" "ws2811_channel_t *""'"); } arg1 = (ws2811_channel_t *)(argp1); result = (int) ((arg1)->invert); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_channel_t_count_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_channel_t *arg1 = (ws2811_channel_t *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:ws2811_channel_t_count_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_channel_t_count_set" "', argument " "1"" of type '" "ws2811_channel_t *""'"); } arg1 = (ws2811_channel_t *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "ws2811_channel_t_count_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->count = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_channel_t_count_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_channel_t *arg1 = (ws2811_channel_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:ws2811_channel_t_count_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_channel_t_count_get" "', argument " "1"" of type '" "ws2811_channel_t *""'"); } arg1 = (ws2811_channel_t *)(argp1); result = (int) ((arg1)->count); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_channel_t_brightness_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_channel_t *arg1 = (ws2811_channel_t *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:ws2811_channel_t_brightness_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_channel_t_brightness_set" "', argument " "1"" of type '" "ws2811_channel_t *""'"); } arg1 = (ws2811_channel_t *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "ws2811_channel_t_brightness_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->brightness = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_channel_t_brightness_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_channel_t *arg1 = (ws2811_channel_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:ws2811_channel_t_brightness_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_channel_t_brightness_get" "', argument " "1"" of type '" "ws2811_channel_t *""'"); } arg1 = (ws2811_channel_t *)(argp1); result = (int) ((arg1)->brightness); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_channel_t_strip_type_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_channel_t *arg1 = (ws2811_channel_t *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:ws2811_channel_t_strip_type_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_channel_t_strip_type_set" "', argument " "1"" of type '" "ws2811_channel_t *""'"); } arg1 = (ws2811_channel_t *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "ws2811_channel_t_strip_type_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->strip_type = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_channel_t_strip_type_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_channel_t *arg1 = (ws2811_channel_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:ws2811_channel_t_strip_type_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_channel_t_strip_type_get" "', argument " "1"" of type '" "ws2811_channel_t *""'"); } arg1 = (ws2811_channel_t *)(argp1); result = (int) ((arg1)->strip_type); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_channel_t_leds_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_channel_t *arg1 = (ws2811_channel_t *) 0 ; ws2811_led_t *arg2 = (ws2811_led_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:ws2811_channel_t_leds_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_channel_t_leds_set" "', argument " "1"" of type '" "ws2811_channel_t *""'"); } arg1 = (ws2811_channel_t *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_unsigned_int, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ws2811_channel_t_leds_set" "', argument " "2"" of type '" "ws2811_led_t *""'"); } arg2 = (ws2811_led_t *)(argp2); if (arg1) (arg1)->leds = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_channel_t_leds_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_channel_t *arg1 = (ws2811_channel_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; ws2811_led_t *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:ws2811_channel_t_leds_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_channel_t_leds_get" "', argument " "1"" of type '" "ws2811_channel_t *""'"); } arg1 = (ws2811_channel_t *)(argp1); result = (ws2811_led_t *) ((arg1)->leds); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_unsigned_int, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_new_ws2811_channel_t(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_channel_t *result = 0 ; if (!PyArg_ParseTuple(args,(char *)":new_ws2811_channel_t")) SWIG_fail; result = (ws2811_channel_t *)calloc(1, sizeof(ws2811_channel_t)); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ws2811_channel_t, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_ws2811_channel_t(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_channel_t *arg1 = (ws2811_channel_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:delete_ws2811_channel_t",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_channel_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_ws2811_channel_t" "', argument " "1"" of type '" "ws2811_channel_t *""'"); } arg1 = (ws2811_channel_t *)(argp1); free((char *) arg1); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *ws2811_channel_t_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_ws2811_channel_t, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_wrap_ws2811_t_device_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *arg1 = (ws2811_t *) 0 ; struct ws2811_device *arg2 = (struct ws2811_device *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:ws2811_t_device_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_t_device_set" "', argument " "1"" of type '" "ws2811_t *""'"); } arg1 = (ws2811_t *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ws2811_device, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ws2811_t_device_set" "', argument " "2"" of type '" "struct ws2811_device *""'"); } arg2 = (struct ws2811_device *)(argp2); if (arg1) (arg1)->device = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_t_device_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *arg1 = (ws2811_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; struct ws2811_device *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:ws2811_t_device_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_t_device_get" "', argument " "1"" of type '" "ws2811_t *""'"); } arg1 = (ws2811_t *)(argp1); result = (struct ws2811_device *) ((arg1)->device); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ws2811_device, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_t_rpi_hw_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *arg1 = (ws2811_t *) 0 ; rpi_hw_t *arg2 = (rpi_hw_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:ws2811_t_rpi_hw_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_t_rpi_hw_set" "', argument " "1"" of type '" "ws2811_t *""'"); } arg1 = (ws2811_t *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_rpi_hw_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ws2811_t_rpi_hw_set" "', argument " "2"" of type '" "rpi_hw_t const *""'"); } arg2 = (rpi_hw_t *)(argp2); if (arg1) (arg1)->rpi_hw = (rpi_hw_t const *)arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_t_rpi_hw_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *arg1 = (ws2811_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; rpi_hw_t *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:ws2811_t_rpi_hw_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_t_rpi_hw_get" "', argument " "1"" of type '" "ws2811_t *""'"); } arg1 = (ws2811_t *)(argp1); result = (rpi_hw_t *) ((arg1)->rpi_hw); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_rpi_hw_t, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_t_freq_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *arg1 = (ws2811_t *) 0 ; uint32_t arg2 ; void *argp1 = 0 ; int res1 = 0 ; unsigned int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:ws2811_t_freq_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_t_freq_set" "', argument " "1"" of type '" "ws2811_t *""'"); } arg1 = (ws2811_t *)(argp1); ecode2 = SWIG_AsVal_unsigned_SS_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "ws2811_t_freq_set" "', argument " "2"" of type '" "uint32_t""'"); } arg2 = (uint32_t)(val2); if (arg1) (arg1)->freq = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_t_freq_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *arg1 = (ws2811_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; uint32_t result; if (!PyArg_ParseTuple(args,(char *)"O:ws2811_t_freq_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_t_freq_get" "', argument " "1"" of type '" "ws2811_t *""'"); } arg1 = (ws2811_t *)(argp1); result = (uint32_t) ((arg1)->freq); resultobj = SWIG_From_unsigned_SS_int((unsigned int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_t_dmanum_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *arg1 = (ws2811_t *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:ws2811_t_dmanum_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_t_dmanum_set" "', argument " "1"" of type '" "ws2811_t *""'"); } arg1 = (ws2811_t *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "ws2811_t_dmanum_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->dmanum = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_t_dmanum_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *arg1 = (ws2811_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:ws2811_t_dmanum_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_t_dmanum_get" "', argument " "1"" of type '" "ws2811_t *""'"); } arg1 = (ws2811_t *)(argp1); result = (int) ((arg1)->dmanum); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_t_channel_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *arg1 = (ws2811_t *) 0 ; ws2811_channel_t *arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:ws2811_t_channel_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_t_channel_set" "', argument " "1"" of type '" "ws2811_t *""'"); } arg1 = (ws2811_t *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ws2811_t_channel_set" "', argument " "2"" of type '" "ws2811_channel_t [RPI_PWM_CHANNELS]""'"); } arg2 = (ws2811_channel_t *)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)RPI_PWM_CHANNELS; ++ii) *(ws2811_channel_t *)&arg1->channel[ii] = *((ws2811_channel_t *)arg2 + ii); } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""channel""' of type '""ws2811_channel_t [RPI_PWM_CHANNELS]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_t_channel_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *arg1 = (ws2811_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; ws2811_channel_t *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:ws2811_t_channel_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_t_channel_get" "', argument " "1"" of type '" "ws2811_t *""'"); } arg1 = (ws2811_t *)(argp1); result = (ws2811_channel_t *)(ws2811_channel_t *) ((arg1)->channel); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_new_ws2811_t(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *result = 0 ; if (!PyArg_ParseTuple(args,(char *)":new_ws2811_t")) SWIG_fail; result = (ws2811_t *)calloc(1, sizeof(ws2811_t)); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ws2811_t, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_ws2811_t(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *arg1 = (ws2811_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:delete_ws2811_t",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_ws2811_t" "', argument " "1"" of type '" "ws2811_t *""'"); } arg1 = (ws2811_t *)(argp1); free((char *) arg1); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *ws2811_t_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_ws2811_t, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_wrap_ws2811_init(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *arg1 = (ws2811_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:ws2811_init",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_init" "', argument " "1"" of type '" "ws2811_t *""'"); } arg1 = (ws2811_t *)(argp1); result = (int)ws2811_init(arg1); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_fini(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *arg1 = (ws2811_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:ws2811_fini",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_fini" "', argument " "1"" of type '" "ws2811_t *""'"); } arg1 = (ws2811_t *)(argp1); ws2811_fini(arg1); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_render(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *arg1 = (ws2811_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:ws2811_render",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_render" "', argument " "1"" of type '" "ws2811_t *""'"); } arg1 = (ws2811_t *)(argp1); result = (int)ws2811_render(arg1); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_wait(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *arg1 = (ws2811_t *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:ws2811_wait",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_wait" "', argument " "1"" of type '" "ws2811_t *""'"); } arg1 = (ws2811_t *)(argp1); result = (int)ws2811_wait(arg1); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_led_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_channel_t *arg1 = (ws2811_channel_t *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; uint32_t result; if (!PyArg_ParseTuple(args,(char *)"OO:ws2811_led_get",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_led_get" "', argument " "1"" of type '" "ws2811_channel_t *""'"); } arg1 = (ws2811_channel_t *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "ws2811_led_get" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); result = (uint32_t)ws2811_led_get(arg1,arg2); resultobj = SWIG_From_unsigned_SS_int((unsigned int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_led_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_channel_t *arg1 = (ws2811_channel_t *) 0 ; int arg2 ; uint32_t arg3 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; unsigned int val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"OOO:ws2811_led_set",&obj0,&obj1,&obj2)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_led_set" "', argument " "1"" of type '" "ws2811_channel_t *""'"); } arg1 = (ws2811_channel_t *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "ws2811_led_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); ecode3 = SWIG_AsVal_unsigned_SS_int(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "ws2811_led_set" "', argument " "3"" of type '" "uint32_t""'"); } arg3 = (uint32_t)(val3); result = (int)ws2811_led_set(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ws2811_channel_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ws2811_t *arg1 = (ws2811_t *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; ws2811_channel_t *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:ws2811_channel_get",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ws2811_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ws2811_channel_get" "', argument " "1"" of type '" "ws2811_t *""'"); } arg1 = (ws2811_t *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "ws2811_channel_get" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); result = (ws2811_channel_t *)ws2811_channel_get(arg1,arg2); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ws2811_channel_t, 0 | 0 ); return resultobj; fail: return NULL; } static PyMethodDef SwigMethods[] = { { (char *)"SWIG_PyInstanceMethod_New", (PyCFunction)SWIG_PyInstanceMethod_New, METH_O, NULL}, { (char *)"ws2811_channel_t_gpionum_set", _wrap_ws2811_channel_t_gpionum_set, METH_VARARGS, NULL}, { (char *)"ws2811_channel_t_gpionum_get", _wrap_ws2811_channel_t_gpionum_get, METH_VARARGS, NULL}, { (char *)"ws2811_channel_t_invert_set", _wrap_ws2811_channel_t_invert_set, METH_VARARGS, NULL}, { (char *)"ws2811_channel_t_invert_get", _wrap_ws2811_channel_t_invert_get, METH_VARARGS, NULL}, { (char *)"ws2811_channel_t_count_set", _wrap_ws2811_channel_t_count_set, METH_VARARGS, NULL}, { (char *)"ws2811_channel_t_count_get", _wrap_ws2811_channel_t_count_get, METH_VARARGS, NULL}, { (char *)"ws2811_channel_t_brightness_set", _wrap_ws2811_channel_t_brightness_set, METH_VARARGS, NULL}, { (char *)"ws2811_channel_t_brightness_get", _wrap_ws2811_channel_t_brightness_get, METH_VARARGS, NULL}, { (char *)"ws2811_channel_t_strip_type_set", _wrap_ws2811_channel_t_strip_type_set, METH_VARARGS, NULL}, { (char *)"ws2811_channel_t_strip_type_get", _wrap_ws2811_channel_t_strip_type_get, METH_VARARGS, NULL}, { (char *)"ws2811_channel_t_leds_set", _wrap_ws2811_channel_t_leds_set, METH_VARARGS, NULL}, { (char *)"ws2811_channel_t_leds_get", _wrap_ws2811_channel_t_leds_get, METH_VARARGS, NULL}, { (char *)"new_ws2811_channel_t", _wrap_new_ws2811_channel_t, METH_VARARGS, NULL}, { (char *)"delete_ws2811_channel_t", _wrap_delete_ws2811_channel_t, METH_VARARGS, NULL}, { (char *)"ws2811_channel_t_swigregister", ws2811_channel_t_swigregister, METH_VARARGS, NULL}, { (char *)"ws2811_t_device_set", _wrap_ws2811_t_device_set, METH_VARARGS, NULL}, { (char *)"ws2811_t_device_get", _wrap_ws2811_t_device_get, METH_VARARGS, NULL}, { (char *)"ws2811_t_rpi_hw_set", _wrap_ws2811_t_rpi_hw_set, METH_VARARGS, NULL}, { (char *)"ws2811_t_rpi_hw_get", _wrap_ws2811_t_rpi_hw_get, METH_VARARGS, NULL}, { (char *)"ws2811_t_freq_set", _wrap_ws2811_t_freq_set, METH_VARARGS, NULL}, { (char *)"ws2811_t_freq_get", _wrap_ws2811_t_freq_get, METH_VARARGS, NULL}, { (char *)"ws2811_t_dmanum_set", _wrap_ws2811_t_dmanum_set, METH_VARARGS, NULL}, { (char *)"ws2811_t_dmanum_get", _wrap_ws2811_t_dmanum_get, METH_VARARGS, NULL}, { (char *)"ws2811_t_channel_set", _wrap_ws2811_t_channel_set, METH_VARARGS, NULL}, { (char *)"ws2811_t_channel_get", _wrap_ws2811_t_channel_get, METH_VARARGS, NULL}, { (char *)"new_ws2811_t", _wrap_new_ws2811_t, METH_VARARGS, NULL}, { (char *)"delete_ws2811_t", _wrap_delete_ws2811_t, METH_VARARGS, NULL}, { (char *)"ws2811_t_swigregister", ws2811_t_swigregister, METH_VARARGS, NULL}, { (char *)"ws2811_init", _wrap_ws2811_init, METH_VARARGS, NULL}, { (char *)"ws2811_fini", _wrap_ws2811_fini, METH_VARARGS, NULL}, { (char *)"ws2811_render", _wrap_ws2811_render, METH_VARARGS, NULL}, { (char *)"ws2811_wait", _wrap_ws2811_wait, METH_VARARGS, NULL}, { (char *)"ws2811_led_get", _wrap_ws2811_led_get, METH_VARARGS, NULL}, { (char *)"ws2811_led_set", _wrap_ws2811_led_set, METH_VARARGS, NULL}, { (char *)"ws2811_channel_get", _wrap_ws2811_channel_get, 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_rpi_hw_t = {"_p_rpi_hw_t", "rpi_hw_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 *|ws2811_led_t *|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 _swigt__p_ws2811_channel_t = {"_p_ws2811_channel_t", "ws2811_channel_t *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ws2811_device = {"_p_ws2811_device", "struct ws2811_device *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ws2811_t = {"_p_ws2811_t", "ws2811_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_rpi_hw_t, &_swigt__p_short, &_swigt__p_signed_char, &_swigt__p_unsigned_char, &_swigt__p_unsigned_int, &_swigt__p_unsigned_long_long, &_swigt__p_unsigned_short, &_swigt__p_ws2811_channel_t, &_swigt__p_ws2811_device, &_swigt__p_ws2811_t, }; 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_rpi_hw_t[] = { {&_swigt__p_rpi_hw_t, 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 _swigc__p_ws2811_channel_t[] = { {&_swigt__p_ws2811_channel_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ws2811_device[] = { {&_swigt__p_ws2811_device, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ws2811_t[] = { {&_swigt__p_ws2811_t, 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_rpi_hw_t, _swigc__p_short, _swigc__p_signed_char, _swigc__p_unsigned_char, _swigc__p_unsigned_int, _swigc__p_unsigned_long_long, _swigc__p_unsigned_short, _swigc__p_ws2811_channel_t, _swigc__p_ws2811_device, _swigc__p_ws2811_t, }; /* -------- 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); SWIG_Python_SetConstant(d, "WS2811_TARGET_FREQ",SWIG_From_int((int)(800000))); SWIG_Python_SetConstant(d, "WS2811_STRIP_RGB",SWIG_From_int((int)(0x100800))); SWIG_Python_SetConstant(d, "WS2811_STRIP_RBG",SWIG_From_int((int)(0x100008))); SWIG_Python_SetConstant(d, "WS2811_STRIP_GRB",SWIG_From_int((int)(0x081000))); SWIG_Python_SetConstant(d, "WS2811_STRIP_GBR",SWIG_From_int((int)(0x080010))); SWIG_Python_SetConstant(d, "WS2811_STRIP_BRG",SWIG_From_int((int)(0x001008))); SWIG_Python_SetConstant(d, "WS2811_STRIP_BGR",SWIG_From_int((int)(0x000810))); #if PY_VERSION_HEX >= 0x03000000 return m; #else return; #endif } ./library/legacy/rpi-ws281x/setup.py0000775000175000017500000000235114223621661020436 0ustar jawn-smithjawn-smith#!/usr/bin/env python # Python wrapper for the rpi_ws281x library. # Author: Tony DiCola (tony@tonydicola.com) from setuptools import setup, find_packages, Extension from setuptools.command.build_py import build_py import subprocess class CustomInstallCommand(build_py): """Customized install to run library Makefile""" def run(self): print("Compiling ws281x library...") subprocess.Popen(["make","-Clib","lib"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) build_py.run(self) setup(name = 'rpi_ws281x', version = '2.0.4', author = 'Jeremy Garff', author_email = 'jer@jers.net', description = 'Userspace Raspberry Pi PWM library for WS281X LEDs.', license = 'MIT', url = 'https://github.com/jgarff/rpi_ws281x/', cmdclass = {'build_py':CustomInstallCommand}, py_modules = ['neopixel'], ext_modules = [Extension('_rpi_ws281x', sources=['rpi_ws281x_wrap.c'], include_dirs=['lib/'], library_dirs=['lib/'], libraries=['ws2811'])]) ./library/legacy/rpi-ws281x/MANIFEST.in0000664000175000017500000000013714223621661020457 0ustar jawn-smithjawn-smithinclude lib/* include setup.py include rpi_ws281x_wrap.c include neopixel.py include README.md ./library/sphinx/0000775000175000017500000000000014223621661015121 5ustar jawn-smithjawn-smith./library/sphinx/.gitignore0000664000175000017500000000001014223621661017100 0ustar jawn-smithjawn-smith_build/ ./library/sphinx/_templates/0000775000175000017500000000000014223621661017256 5ustar jawn-smithjawn-smith./library/sphinx/_templates/layout.html0000664000175000017500000000023214223621661021456 0ustar jawn-smithjawn-smith{% extends "!layout.html" %} {% block extrahead %} {% endblock %}./library/sphinx/_templates/breadcrumbs.html0000664000175000017500000000000014223621661022423 0ustar jawn-smithjawn-smith./library/sphinx/index.rst0000664000175000017500000000310114223621661016755 0ustar jawn-smithjawn-smith.. role:: python(code) :language: python .. toctree:: :titlesonly: :maxdepth: 0 Welcome ------- This documentation will guide you through the methods available in the Unicorn HAT python library. Unicorn HAT is a Raspberry Pi add-on with 64 individually controllable RGB LEDs. * More information - https://shop.pimoroni.com/products/unicorn-hat * GPIO pinout - https://pinout.xyz/unicorn_hat * Get the code - https://github.com/pimoroni/unicorn-hat * Get started - https://learn.pimoroni.com/tutorial/unicorn-hat/getting-started-with-unicorn-hat * Get help - http://forums.pimoroni.com/c/support At A Glance ----------- .. automoduleoutline:: unicornhat :members: Brightness ---------- .. autofunction:: unicornhat.brightness Clear ----- .. autofunction:: unicornhat.clear Get Brightness -------------- .. autofunction:: unicornhat.get_brightness Get Pixel --------- .. autofunction:: unicornhat.get_pixel Get Pixels ---------- .. autofunction:: unicornhat.get_pixels Get Shape --------- .. autofunction:: unicornhat.get_shape Turn Off -------- .. autofunction:: unicornhat.off Rotation -------- .. autofunction:: unicornhat.rotation Set All ------- .. autofunction:: unicornhat.set_all Set Layout ---------- .. autofunction:: unicornhat.set_layout Set Pixel --------- .. autofunction:: unicornhat.set_pixel Set Pixel HSV ------------- .. autofunction:: unicornhat.set_pixel_hsv Set Pixels ---------- .. autofunction:: unicornhat.set_pixels Shade Pixels ------------ .. autofunction:: unicornhat.shade_pixels Show ---- .. autofunction:: unicornhat.show ./library/sphinx/shop-logo.png0000664000175000017500000004630414223621661017545 0ustar jawn-smithjawn-smithPNG  IHDR.Kj pHYs  9iTXtXML:com.adobe.xmp Adobe Photoshop CC 2015 (Macintosh) 2016-11-11T18:29:08Z 2016-11-11T18:52:03Z 2016-11-11T18:52:03Z image/png 3 xmp.iid:853b42bb-b828-422f-b4f7-b8f372953397 xmp.did:8c4c5b6d-ef37-4979-9175-582fe48a3c22 xmp.did:8c4c5b6d-ef37-4979-9175-582fe48a3c22 created xmp.iid:8c4c5b6d-ef37-4979-9175-582fe48a3c22 2016-11-11T18:29:08Z Adobe Photoshop CC 2015 (Macintosh) saved xmp.iid:853b42bb-b828-422f-b4f7-b8f372953397 2016-11-11T18:52:03Z Adobe Photoshop CC 2015 (Macintosh) / 1 720000/10000 720000/10000 2 65535 302 75 J cHRMz%u0`:o_FrIDATx]RMo(' ,\OTqVQ2LDD8"*9@ֽ=\@dz=tH;?3B%K,-,Y*y%~rnQ]I1Y#ْŻERCy7fkk}upɘ0.#2HAqe{h4t%!?o]xב/Ii0tѷTck<BFKB.erTW>m!օ>F%c5nU!aҕb7! \ 's1@o"_ ! ^ yЀ6Ȟp+Jz:vqЙdM\cvj2>CZȇʄw7A[4=clۘ?QqyuF&\gO9< LkqEC"p8vvJ{gr QsT輨W))}Z*Ej .%c9+C3NZmWQ ?IE2Y;7:OaM0٠`6h.Nw /Hn1hFl; 4Cp,Zo(Þ2ʆJF7`9Ӥ@7SIhK\u$JF]CF(@st\%A` 6^A. !KǕ KԽJAmFpq.踨#I@Q:Үqc SPCH&Vd!c03hgr\3ӝ=w`u,(XNM(ۨU4A%ozd\5@xvG8.9ߋ{{vh`D)am^ٚ8.`H|Yd:f>8+YEp\j'$G9.N^t`Ms/N8] rSdm-t\hEBg,ӄ."Y|T$!7SPwV3HYnWJG9T,WѢkp]֣ܺ^/E\3"~o86pąYiXH'$x7]&uAıq9Og!V渲~F>1ѕI]dF+Mѐm}{xsQ,JcVkHy)5$u2Soɋ)RTΙ֩Ir_iA^k7L6悰+!Ec`g[ *'y5+_1xE'i-Gu2Bz5TQ>0}tL%76PH:9/_ZOv\ v ( #?`[-ALN_R+AƉOb!W3)TM#tw-YBf?~:⿔ߤk8T 7rX[iNL^l3Y;.ps缉ç Lَdp3*&[CwbSOr\k4w~-S1#SY|H .gb?2,dXP)-ɍBu ܐdCb>f4A3 ~ Q8k]UOӿVCM^9v MI]6y0 6H"A3L}"T^#7\1YUH~ϡe]5x0ʭ^mW9`EiU +_o :?LUT{߀Y:m.&O ~usϮ?!cU!ġ^C\ n"3 :WOv#P=~Mx8J^GʰW<%@{Q\BR ?WSļxܣA$ʂbC稇i+7Jo !TɭMxZR[{mx,Ydndɒu\,Yd%K,Yeɒ%,Yd:.K,Y˒%KqYdɒu\,YdF[;u;N3Xtctz$v`ws%+Xq{|pzNV OSN99v/p<_gFsަ(6t &!Vtb?#rx0vnۺHt@gC?|N*qn~V^k%s)82q%Q DS^wx!zQϓtsykPH;-Rƾ&dfR5_: +1e!Kw-!',u/}^ %5:+k2 <9xo K 7N9Pꅇ|mB0X1pRS7~B[/~ ;uOT4n|ͷ8LPşF:!:,:;ih$L}CCKPER%_~B#.4%U~g>Vnq51C#Bx9Дx1wzE=CCZH@ <>Ub-\ŰG 0>=}lG tw,& 9;u⌕1}!rZɒ)h0?|+! YWdMӅ9Tu4F  L+pT gaՐG;Vmg/)?& :#l*4]xkQ3ۜn+L/ADp\}iyavBP|A8I,I{'Pհ~cIe i8=Z3n/쌴sU4=;wawݠp&>cm44J,(J3~qaL![_Dh +kZ#YWh B]4 I[(sη@Oge^x#K/?ߺ3?@6$I'b/NH]]po Jq+94E?+'@ف"1{xYMYwYRE3eEc:BEii0:^PZK:Ƙph?E6IJ:6 )H3&y2&=Gw\~706XK)h:8<%zX9=gG>+1GJDP[SldE@NY~OWҥ`i_Ҵ! ocQ@?mEpK*$1uF5qm2楒i>5݄8KL Oeu~[qJkjR tH vVAwz7 ^Vt?8 Ee}B|Esl3Rg "dj- D>NP"zbFIcHA^82a 3 m- ri|NX&Dd͠3L.ѵVF_h:|m`Ա!e^Ѵn읓ڞD qbsp_6;!/i"NoN\9ڙNnmwKsR_`S3̑ɥ& 裐e9|ԝ#6ᯁy@$!W? z']sS2nLS[z :0xY>^A{ХY@=L)ҪK2) RCRIy2uOH5CAP1ؐqK=$|* 9%$)G)HF#@ c^j"jfᷯwmme"٤'k(`HHH۲);uboF򆡫TU}-9)YDLjYSF v}XXwM|uc:"^2Q6hʔS >yWɒғHc4U[* 7!kvy,jB'ʡ\NjXZ27%gVtd}IY.:0bXYѽv$u Oυ?,H[*7 ڊԗIENDB`./library/sphinx/conf.py0000664000175000017500000002542414223621661016427 0ustar jawn-smithjawn-smith#-*- coding: utf-8 -*- import sys import site import mock # Prompte /usr/local/lib to the front of sys.path #sys.path.insert(0,site.getsitepackages()[0]) import sphinx_rtd_theme sys.modules['neopixel'] = mock.Mock() sys.path.insert(0, '../UnicornHat/') 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' import unicornhat PACKAGE_NAME = u"Unicorn HAT" PACKAGE_HANDLE = "UnicornHAT" PACKAGE_MODULE = "unicornhat" if hasattr(unicornhat,"__version__"): PACKAGE_VERSION = unicornhat.__version__ else: PACKAGE_VERSION = "x.x.x" # -- 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'2016, 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(PACKAGE_VERSION) # The full version, including alpha/beta/rc tags. release = u'{}'.format(PACKAGE_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 ./library/sphinx/_static/0000775000175000017500000000000014223621661016547 5ustar jawn-smithjawn-smith./library/sphinx/_static/custom.css0000664000175000017500000000172414223621661020577 0ustar jawn-smithjawn-smith.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-unicornhat { margin-bottom:24px; } .rst-content #module-unicornhat dl:not(.docutils) dt { border:none; background:#f0f0f0; } .rst-content #module-unicornhat dl:not(.docutils) dd { display:none; } .rst-content #module-unicornhat dl:not(.docutils) { margin-bottom:0; } ./library/sphinx/favicon.png0000664000175000017500000006270114223621661017262 0ustar jawn-smithjawn-smithPNG  IHDR>a pHYs.#.#x?v MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3CiTXtXML:com.adobe.xmp adobe:docid:photoshop:fbc3c8e6-f499-11e4-982c-e3603a9ded66 xmp.iid:d4307829-eda0-234a-9ca8-413b9a65231e 01400FB090F48020FFF87DB561DE2A99 saved xmp.iid:c6d3c71f-c7c6-4576-bc57-4a8c3d8c114d 2015-04-29T11:08:22+01:00 Adobe Photoshop CC 2014 (Macintosh) / saved xmp.iid:86a827fa-c470-0244-9d51-af6d22cc8635 2015-05-07T10:18:48+01:00 Adobe Photoshop CC 2014 (Windows) / converted from image/jpeg to image/png derived converted from image/jpeg to image/png saved xmp.iid:af252d3b-ac2c-ec4a-8059-071e71a35f2b 2015-05-07T10:18:48+01:00 Adobe Photoshop CC 2014 (Windows) / saved xmp.iid:d4307829-eda0-234a-9ca8-413b9a65231e 2015-05-07T10:21:41+01:00 Adobe Photoshop CC 2014 (Windows) / xmp.iid:86a827fa-c470-0244-9d51-af6d22cc8635 01400FB090F48020FFF87DB561DE2A99 01400FB090F48020FFF87DB561DE2A99 image/png C75D17E574B56EF5DBBE3994C0E9795C 3 sRGB IEC61966-2.1 2015-04-29T11:07:12+01:00 2015-05-07T10:21:41+01:00 2015-05-07T10:21:41+01:00 Adobe Photoshop CC 2014 (Windows) 3508 2480 8 8 8 2 1 3 3000000/10000 3000000/10000 2 0221 1 128 128 L; cHRMz%u0`:o_F`IDATx{]WuksխV-Y-Y-!Q I'ԤHdf*5ƕL 20 xTI!#c$lIZ}㜽qn˲"|*Uܳ׷k*wo;@ Ȱh)pxx^L$&ׁw3Y,)4pr @.[%&yශAwX5C3BQd--[S!@pon+ $3?̄"qoKFw_V2op#pJ;$|J x e_%bzt|k -|o"&Z>%y'I|9Aw1UQ 2}NѺ V &^+3T3Z"D6{l_&lM`-ÖU51<;!隍Oxs4=ScWAt;tSZR[GU5 ">4Ԓ3\a-c}ow^s+;*D(,l5I`]Bcv a4,bm⛂NqGN}oiL jFmoG6G r&UD*q Sǘ <9~ \2wUwCT $HHc]0h/0?sn8@RN#bZߏ&kNP~KLra (^W-45D@AHD Qʵvg~~ S\t \- 7-^6Q av=r}Jj6v`>QeL`L>gxFr(J725ux6_8T@]K[)^=}NLcyw\cA@R&zC-%,T\g$۰"@sl4jA\(ަw80U^=*%871z<ȒˆQAr@|ٖG+XE4u'c8f/V8j 0Է QhFsόVISາ Y^Iv^b Xk$m#MxkBNx̙ #_=4ӰTW2 FD$?{C>GFpP b`VjxM"DPl[yf/m86z84RG\<a޷p(*{'/ "4x F 9NO'[773EOc ܜĞ(ǧ?/jh؝lMU 1h|ĴBęu$ HjIN)_cϣ=<5Z(`I1> 5PFM8DGYy~'xtXp#Y>B`Lk&$QI\LpRǷ^qÍ.eB{^tOF۠1Fimqt~·XrաޱapQj^¢5P9{Oa*7}L~h|Z0ℇg ujO rc 'L`V.W*qlV55[|N+F%$t2PT>}W``ݨwzj]TUGmy-{/7lY%X笮E٣cg] K"÷l)CUΑ* ^( ύNt І_*=[1JLEvl`5Zˣ?q(f^o>! Ѯehh+:U.wm0irOȣO]Hxzt*#f@*gy o@Jp|b5#R'A 3`ņbӪexb+nfK>01YGt|5Bphͮ~jqE&VA,"~xgLQS7X,y`9:%̦n' 0WE!uN_$f(^hdXʘM=yx;S=#6] LS a gw|^ L%AFeH* zt??9 Ʋ?[6c#FVxlZZr@Ӂ\ B3]liUmר۹{'ˑ:_;{=E"py8D??L00rE޼f_v TH+)=7Gc`_ݺԣbVbtcX@xى$@_/a뾭q=i3\K5>t('1*b(M qݷ00w!I:JӇx?YO(9] 2.Zs?Tsӌi|S58q1*P^ny8Dr/mOE9p =f-\ƙc5UȈ,JBjfo0xȐkiGi:DW,+oCFr}n:tJE;nrJu%*͛.`ZEvAXt F̡Z/DQׇ/p:BD,ETi!9Eir8g;^$@5xf,'wiV/~z Sm$|YnL%(PiSW>Lx\,<| Z)sk+ܷ+W>CXLOޢGxFu:0TguEPDMᬜc{㓫ő <6:Ή& E5ē`̉n.\qgo/w1czr]%t Ā/5I .pUy򫰵j[brHޏp6jZɤN# зm#Wy*aZݢPm5TPEAsU_[$`Pa͟^ 3cSDY< ik~T6, X!_tzI{a3 Y ?Ȑ CF 2dȐ CF 2dȐ CF 2dȰ .[Q@5#r#&s߽iQǣZn0AC٬XNP ig~H|_?&̯#@s! GsH\6۳F=<o4 0_tORyI^l{եN/$|\ڊK2+! $T殽w3QE/t{ľy;#L h*|*l08l/#蔜C/ t[T:a\`hw>;~-_4# fy7^ҨmR{oaf,U51`BƃN<M1|pWwݶHufq*f |pastT3ć!q ~V7M.|@ ǀ x2t'WZ4Hٻ;2un M&n -#Y Wg볢qod%|6[UZ倯f뵢083!ko5[1LWsį)3s"YྖL-bW[qaxWKB`7x$üْn3ٷwS+T7lN_Vg67_;[L |8ǡ~EOԮ [IENDB`./library/UnicornHat/0000775000175000017500000000000014223621661015662 5ustar jawn-smithjawn-smith./library/UnicornHat/unicornhat.py0000664000175000017500000002271714223621661020417 0ustar jawn-smithjawn-smithimport atexit import colorsys from rpi_ws281x import __version__ as __rpi_ws281x__, PixelStrip, Color __version__ = '2.2.3' # LED strip configuration: LED_COUNT = 64 # Number of LED pixels. LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!). LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) LED_DMA = 10 # DMA channel to use for generating signal LED_BRIGHTNESS = 128 # Set to 0 for darkest and 255 for brightest LED_CHANNEL = 0 # PWM channel LED_INVERT = False # True to invert the signal (when using NPN transistor level shift) LED_GAMMA = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 21, 21, 22, 22, 23, 23, 24, 25, 25, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33, 34, 34, 35, 36, 37, 37, 38, 39, 40, 40, 41, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 76, 77, 78, 79, 80, 81, 83, 84, 85, 86, 88, 89, 90, 91, 93, 94, 95, 96, 98, 99,100,102,103,104,106,107,109,110, 111,113,114,116,117,119,120,121,123,124,126,128,129,131,132,134, 135,137,138,140,142,143,145,146,148,150,151,153,155,157,158,160, 162,163,165,167,169,170,172,174,176,178,179,181,183,185,187,189, 191,193,194,196,198,200,202,204,206,208,210,212,214,216,218,220, 222,224,227,229,231,233,235,237,239,241,244,246,248,250,252,255] COLORS = { 'red':(255,0,0), 'lime':(0,255,0), 'blue':(0,0,255), 'yellow':(255,255,0), 'magenta':(255,0,255), 'cyan':(0,255,255), 'black':(0,0,0), 'white':(255,255,255), 'gray':(127,127,127), 'grey':(127,127,127), 'silver':(192,192,192), 'maroon':(128,0,0), 'olive':(128,128,0), 'green':(0,128,0), 'purple':(128,0,128), 'teal':(0,128,128), 'navy':(0,0,128), 'orange':(255,165,0), 'gold':(255,215,0), 'purple':(128,0,128), 'indigo':(75,0,130) } """ Store the rotation of UnicornHat, defaults to 0 which places 0,0 on the top left with the B+ HDMI port facing downwards """ _rotation = 0 _requested_rotation = 0 _wx = 8 _wy = 8 _map = [] _pixels = [(0,0,0) for x in range(64)] _is_setup = False ws2812 = None """ Store a map of pixel indexes for translating x, y coordinates. """ HAT = [ [7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ], [8 , 9 , 10, 11, 12, 13, 14, 15], [23, 22, 21, 20, 19, 18, 17, 16], [24, 25, 26, 27, 28, 29, 30, 31], [39, 38, 37, 36, 35, 34, 33, 32], [40, 41, 42, 43, 44, 45, 46, 47], [55, 54, 53, 52, 51, 50, 49, 48], [56, 57, 58, 59, 60, 61, 62, 63] ] PHAT_VERTICAL = [ [0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 ], [8 , 9 , 10, 11, 12, 13, 14, 15], [16, 17, 18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29, 30, 31] ] PHAT = [ [24, 16, 8, 0], [25, 17, 9, 1], [26, 18, 10, 2], [27, 19, 11, 3], [28, 20, 12, 4], [29, 21, 13, 5], [30, 22, 14, 6], [31, 23, 15, 7] ] AUTO = None def setup(): global ws2812, _is_setup if _is_setup: return ws2812 = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_GAMMA) ws2812.begin() set_layout(HAT) atexit.register(_clean_shutdown) _is_setup = True def set_gamma(gamma): setup() ws2812.setGamma(gamma) def disable_gamma(): setup() set_gamma(list(range(256))) def set_layout(pixel_map = AUTO): """Set the layout to Unicorn HAT or Unicorn pHAT Note: auto detection relies upon the HAT EEPROM. Your Unicorn HAT must be connected before boot to successfully auto detect. :param pixel_map: Choose the layout to set, can be either HAT, PHAT, PHAT_VERTICAL or AUTO """ global _map if pixel_map is None: pixel_map = PHAT # Assume PHAT try: product = open("/proc/device-tree/hat/product","r").read().strip() if product[:11] == "Unicorn HAT": pixel_map = HAT except IOError: pass _map = pixel_map def get_shape(): """Returns the shape (width, height) of the display""" global _map setup() # Shape is unset until this is called return (len(_map), len(_map[0])) def _clean_shutdown(): """Registered at exit to ensure ws2812 cleans up after itself and all pixels are turned off. """ off() def rotation(r=0): """Set the display rotation :param r: Specify the rotation in degrees: 0, 90, 180 or 270 """ global _map global _rotation global _requested_rotation setup() if r in [0, 90, 180, 270]: _requested_rotation=r wx = len(_map) wy = len(_map[0]) if wx == wy: _rotation = r else: if r in [0, 180]: _map = PHAT _rotation = r else: _map = PHAT_VERTICAL _rotation = r-90 return True else: raise ValueError('Rotation must be 0, 90, 180 or 270 degrees') def get_rotation(): """Get the display rotation value Returns an integer, either 0, 90, 180 or 270 """ return _requested_rotation def brightness(b=0.2): """Set the display brightness between 0.0 and 1.0 0.2 is highly recommended, UnicornHat can get painfully bright! :param b: Brightness from 0.0 to 1.0 (default 0.2) """ setup() if b > 1 or b < 0: raise ValueError('Brightness must be between 0.0 and 1.0') """Absolute max brightness has been capped to 50%, do not change this unless you know what you're doing. UnicornHAT draws too much current above 50%.""" brightness = int(b*128.0) if brightness < 30: print("Warning: Low brightness chosen, your UnicornHAT might not light up!") ws2812.setBrightness(brightness) def get_brightness(): """Get the display brightness value Returns a float between 0.0 and 1.0 """ setup() return round(ws2812.getBrightness()/128.0, 3) def clear(): """Clear the buffer""" setup() for x in range(64): ws2812.setPixelColorRGB(x, 0, 0, 0) _pixels[x] = (0, 0, 0) def off(): """Clear the buffer and immediately update UnicornHat Turns off all pixels. """ clear() show() def get_index_from_xy(x, y): """Convert an x, y value to an index on the display :param x: Horizontal position from 0 to 7 :param y: Vertical position from 0 to 7 """ setup() wx = len(_map) - 1 wy = len(_map[0]) - 1 y = (wy)-y if _rotation == 90 and wx == wy: x, y = y, (wx)-x elif _rotation == 180: x, y = (wx)-x, (wy)-y elif _rotation == 270 and wx == wy: x, y = (wy)-y, x try: index = _map[x][y] except IndexError: index = None return index def set_pixel_hsv(x, y, h, s=None, v=None): """Set a single pixel to a colour using HSV :param x: Horizontal position from 0 to 7 :param y: Veritcal position from 0 to 7 :param h: Hue from 0.0 to 1.0 ( IE: degrees around hue wheel/360.0 ) :param s: Saturation from 0.0 to 1.0 :param v: Value (also known as brightness) from 0.0 to 1.0 """ if type(h) is tuple: h, s, v = h r, g, b = [int(n*255) for n in colorsys.hsv_to_rgb(h, s, v)] set_pixel(x, y, r, g, b) def set_pixel(x, y, r, g=None, b=None): """Set a single pixel to RGB colour :param x: Horizontal position from 0 to 7 :param y: Veritcal position from 0 to 7 :param r: Amount of red from 0 to 255 :param g: Amount of green from 0 to 255 :param b: Amount of blue from 0 to 255 """ setup() if type(r) is tuple: r, g, b = r elif type(r) is str: try: r, g, b = COLORS[r.lower()] except KeyError: raise ValueError('Invalid color!') index = get_index_from_xy(x, y) if index is not None: ws2812.setPixelColorRGB(index, r, g, b) _pixels[index] = (r, g, b) def get_pixel(x, y): """Get the RGB value of a single pixel :param x: Horizontal position from 0 to 7 :param y: Veritcal position from 0 to 7 """ index = get_index_from_xy(x, y) if index is not None: return _pixels[index] def set_all(r, g=None, b=None): """Set all pixels to a specific colour""" shade_pixels(lambda x, y: (r, g, b)) def shade_pixels(shader, *args): """Set all pixels using a pixel shader style function :param shader: A function which accepts the x and y positions of a pixel and returns a tuple (r, g, b) For example, this would be synonymous to clear:: set_pixels(lambda x, y: return 0,0,0) Or perhaps we want to map red along the horizontal axis, and blue along the vertical:: set_pixels(lambda x, y: return (x/7.0) * 255, 0, (y/7.0) * 255) """ width, height = get_shape() for x in range(width): for y in range(height): r, g, b = shader(x, y, *args) set_pixel(x, y, r, g, b) def set_pixels(pixels): """Set all pixels using an array of `get_shape()`""" shade_pixels(lambda x, y: pixels[y][x]) def get_pixels(): """Get the RGB value of all pixels in a 7x7x3 2d array of tuples""" width, height = get_shape() return [[get_pixel(x, y) for x in range(width)] for y in range(height)] def show(): """Update UnicornHat with the contents of the display buffer""" setup() ws2812.show() ./library/UnicornHat/README.md0000664000175000017500000000153014223621661017140 0ustar jawn-smithjawn-smithUnicorn Hat Python Library ========================== This library wraps the ws281x python driver for UnicornHat, handling conversion of X/Y coordinates to pixel index and exposing the basic methods you need to set pixels and update UnicornHat. Installing ---------- **PIP** sudo pip install unicornhat **GitHub** sudo ./setup.py install Usage ----- Just import unicornhat, then all you need is: * unicornhat.set_pixel( x, y, red, green, blue ) - Set a pixel in the buffer to the specified colour * unicornhat.show - Update UnicornHat with the current buffer * unicornhat.clear - Turn off all the pixels in the buffer and update UnicornHat Unicorn pHAT ------------ For use with the pHAT version type this in at the top of your file to set the board mode: * unicorn.set_layout(unicorn.PHAT) See the examples for more advanced usage. ./library/UnicornHat/README.txt0000664000175000017500000000016714223621661017364 0ustar jawn-smithjawn-smithLearn more: https://shop.pimoroni.com/products/unicorn-hat Learn more: https://shop.pimoroni.com/products/unicorn-phat ./library/UnicornHat/LICENSE.txt0000664000175000017500000000210314223621661017501 0ustar jawn-smithjawn-smithMIT 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. ./library/UnicornHat/CHANGELOG.txt0000664000175000017500000000170614223621661017716 0ustar jawn-smithjawn-smith2.2.2 ----- * Bugfix: Switched to DMA channel 10 to avoid SD card locking + freezing 2.2.1 ----- * Refactor: Switched to using rpi_ws218x 3.x.x 2.1.3 ----- * Feature: Added set_all and shade_pixels which now drives set_pixels * Feature: Added PHAT_VERTICAL optional orientation * Bugfix: get_brightness now returns value * Bugfix: get_pixels now takes into account pHAT/HAT shape 2.1.2 ----- * Added AUTO set_layout which attempts to detect uHAT via EEPROM * Added get_shape() which returns a tuple of width/height 2.1.1 ----- * Initialized to 128 brightness (max) 2.1.0 ----- * Added Unicorn pHAT support 2.0.7 ----- * Added warning on low brightness 2.0.6 ----- * Indent bugfix 2.0.5 ----- * Max brightness capped at 50% * Added requirement for latest 1.0.0 rpi_ws281x ( dubbed 2.0.0 on pip ) 2.0.0 ----- * Major switch over to rpi_ws281x library * Raspberry Pi 2 compatibility 1.0.1 ----- * Fix to rotation() 1.0.0 ----- * Initial Release ./library/UnicornHat/setup.py0000775000175000017500000000425314223621661017403 0ustar jawn-smithjawn-smith#!/usr/bin/env python """ Copyright (c) 2014 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 = 'unicornhat', version = '2.2.3', author = 'Philip Howard', author_email = 'phil@pimoroni.com', description = """Python library for UnicornHAT/pHAT""", long_description= open('README.txt').read() + "\n" + open('CHANGELOG.txt').read(), license = 'MIT', keywords = 'Raspberry Pi Unicorn HAT', url = 'http://shop.pimoroni.com', classifiers = classifiers, py_modules = [ 'unicornhat' ], install_requires= ['rpi_ws281x >= 3.0.3'] ) ./library/UnicornHat/MANIFEST.in0000664000175000017500000000014414223621661017417 0ustar jawn-smithjawn-smithinclude CHANGELOG.txt include LICENSE.txt include README.txt include setup.py include unicornhat.py ./library_c/0000775000175000017500000000000014223621661014112 5ustar jawn-smithjawn-smith./library_c/unicorn/0000775000175000017500000000000014223621661015567 5ustar jawn-smithjawn-smith./library_c/unicorn/Makefile0000664000175000017500000000047114223621661017231 0ustar jawn-smithjawn-smith.PHONY: all clean ws281x_path = ../unicornd/rpi_ws281x all: unicorn $(ws281x_path)/libws2811.a: scons -C $(ws281x_path) unicorn: $(ws281x_path)/libws2811.a unicorn.c gcc -Wall unicorn.c -o unicorn -I$(ws281x_path) -L$(ws281x_path) -lm -lws2811 -lpng clean: scons -C $(ws281x_path) --clean -rm -f unicorn ./library_c/unicorn/README.md0000664000175000017500000000207014223621661017045 0ustar jawn-smithjawn-smithUnicorn Hat C Example ===================== This simple C program will let you display PNG files on your Unicorn Hat, and even run frame-based animations with them. Getting Started --------------- You'll need to install libpng: sudo apt-get install libpng-dev Then make the binary: make Then try displaying an animation: sudo ./unicorn anim/rainbow.png You can change the animation speed by specifying a delay between frames: sudo ./unicorn anim/rainbow.png 500 And you can change the brightness by specifying a value between 0 and 255: sudo ./unicorn anim/rainbow.png 500 1 Demo Pattern ------------ By default, unicorn will display a swirly rainbow pattern demo. sudo ./unicorn You can try different brightnesses by adding them on as a parameter from 0 to 255: sudo ./unicorn 50 Notes ----- If you plan on writing your own C applications to control ws2812 LEDs then please pay special attention to how unicorn.c handles exit signals and terminates cleanly. You absolutely must call terminate() on the ws2812 library when exiting! ./library_c/unicorn/anim/0000775000175000017500000000000014223621661016513 5ustar jawn-smithjawn-smith./library_c/unicorn/anim/photon.png0000664000175000017500000000401514223621661020530 0ustar jawn-smithjawn-smithPNG  IHDRx@O$tEXtSoftwareAdobe ImageReadyqe<&iTXtXML:com.adobe.xmp m}IDATxVKoUڱ8MJR MADDF٠"`S ذcC5YBeC7<$B$,Ҧ"AGm2R Vo!{Q"+Z2WAa-yZUoe.ZUW/`aGJ,3>Sγ%F@z"8\ uQ YE[0o <Ο()@ .bw p&p _Ky XA6p#'-Kdz ]Oѹ [!M0z:TanžE6lSo)}u823g>1`X`Xق%FDQJ:/Mz;Kޡ w]`;F/ԑu ao tb}>p+$}i=4:+V m4ʹؕP؞ ; */c}@}VupYcF2O=Ls61(gI ˛XL;{2 ?TcZß eaLi^o <ל^Y(.ى hR0ZU" A膖[tUTfF!U1Gs=Vc s+e?=ܩ\n #"{씥Oǯ'c|W1kϦx){=<#_]|ET2t/Kp6Ԍv.RG(Gh5u\ww,~&#>L* h(ѕQj$$LrНe-J;FjhSO܂'#qV-yCg & ĴU l6SNӓDE\wmm 䍾 4%QF3/f ֑Smbܜc0 Puhʻu9B۩tzrrvD.]h{h/IENDB`./library_c/unicorn/anim/trip.png0000664000175000017500000001121314223621661020175 0ustar jawn-smithjawn-smithPNG  IHDRZ7htEXtSoftwareAdobe ImageReadyqe<&iTXtXML:com.adobe.xmp E҈IDATx\8 tTU~{U*TTBHB: DM@z\qE[lChmQYۅi`<(C#0," d!!ZKR?UU:Uuw|yۺ;7H:ik+ɅIūNGg70 [b\08xc8yK7.M\KָSiڙ-oSa{/y"@V`@x6G2v=#'I4"={0>?|NSL 6.b?!G-ZU@Df| I$ M,j&4pcLI=L1Q¦d}#/PJp(l IS?!Lڵs^Yay@:%y)nI˰Y'H'w~MG(/)K wWN\s1 r~?f# 2}B<_pc8:)oՑoź8$ z ${I 6M!v65fָ ,Ɨ&)pzw=! ĕ}v@#=X&6cS&?l_թ`t.0m9qÜ}=Bץ劑}*gBc E~.,(HbRXU#Q赦Yqho904yؽ'b^rƚ练=R2`vOsq79\v갗( ˄^"="QP2vrڝaA9vT9VSk2 '1, !(Dqg_|X0e*J,;Rs< :W垽3 ,g|S{r5ҫdO!bUxQ;92"y+?QA X/l,7(2syǯ'ʅ @4l%㽹2)0⿖ɛ?P ʸҴ]Y-a^>uwʡbӨG$r yvK9A t{ jc{01U(.vɃ[؆=Г_ϸ#Z:tgl.&t8h['Yl0.cLc%y"z_lcKV~]gP%KZ1H4*o.o;nV22<"^2̷)0wlƯ+b?+X}^ە&+\̄䌐w7CrΎǀ_zl{Pdr׷,B\ĦMm*z{l%E>rb>'4xt|G|U3H x4'Lqk0=㒛 peoטI}}`?B ڔ0T(zh򱒬Q{Ϗ7Ϫa!mnvys]oݴW.΍v8k;HH4 #?z=tvHWW:1LΘQ]W"ڈ,cNjkN֕Eޔ\&=^+a]iA/9`tzes)IPIXVQ2g4bva8i"J3,HKteؤ"uKc4c0b;x=Kxlkܥ_THsKl'!ZskTqwĆg-480RxH"a(qgTgbuDŰk;]tэ$VLw56#CH/V$gD:p?N43j׈ e$Ч"/k/(cX`B>'|@a#j@%ӱ鉬o7 ugD[PȸV|dPPRąT-Iġ^7G@$ƛ*׫^UxeI CcYe>ZA$SPG2vEyLLHx[@ (KD weI 8X5˶c*&`)))uyč QFE\jcT7?~KJVUF\>຃$F%9;V_P o@:*ʜWTp6F8@r R0$ ^Nzz'?(wOo>\&Z.ÜpDٞxd* 8G beҝi[F3mt7d +oJ;Ӵǡ%ݯc\Qw@in=zVXT OihiE"@_i4 Rj}X곱|wNE")%t`-FZ=.ɒ<:> E`]' ՊW^yGMLL bT]t5ϛSwv)ZUH8 qIq)'Vпnߙ\IXwQ" ;Fu'2 EՏ_|k 3 XlU+l, B;QD=ukZ]qM 7W y4WuyO{mG̟Zۖ YB8-xjg.j+$YNԓNՇOA-ǍPDHR.Yꊮ"YFKF)G 7N*~7tNk*sghzYA|Qj؅x 98g}>?:6R̯IgΟ -%fYOXDrkOhhr7mSfP$ spiUu)>zb"c'Y*T. "DNZq@ ~a^Vx?tTaLyB4 Ϝiz/[8'̑ ʼ?TO U Q ەaj[ w9~bA5vVuļUj6x{k]/+$b4^gH^N GKq88yᎇ%iې-f8jDGHGge޶)m [tÖuiOC2T [ 0clʲWXQaHP1v~ņ(ѕA` ]e 5Mv6EDe(j> ~Lj?2EÎ1py{Y]:}A՜(S38 2E_iP%Vӯs*d”ZPq M4LoқE]RP0t|Y޹Q{CҢ^ꜤjdhkM^YO E K+)bR\(/IENDB`./library_c/unicorn/anim/redblue.png0000664000175000017500000000175014223621661020646 0ustar jawn-smithjawn-smithPNG  IHDR tEXtSoftwareAdobe ImageReadyqe<&iTXtXML:com.adobe.xmp fXIDATxbd0π!ĀCs+?Ɛn9V dޞbD@=`F(TQ-8@}]IENDB`./library_c/unicorn/anim/umbrella.png0000664000175000017500000000215114223621661021023 0ustar jawn-smithjawn-smithPNG  IHDR@ftEXtSoftwareAdobe ImageReadyqe<&iTXtXML:com.adobe.xmp ڋIDATxڔ ExgpG\4N]&Տ޵&H{_ŀR|lL3Jݹc"]/*X.Jɕd9Et\|@+`ݶ99@EAw#de(_G_yjɁRnwvhhaWQC_?31y8W)+Kdp2.Ԋo8h`H@O2ɊIENDB`./library_c/unicorn/anim/nyan.png0000664000175000017500000000233714223621661020173 0ustar jawn-smithjawn-smithPNG  IHDR@ftEXtSoftwareAdobe ImageReadyqe<&iTXtXML:com.adobe.xmp h1OIDATxtAJPuXL,܊pQɅhl+8N6D~w{5MM6ڍ, G?kI7Y<]H,*+wp&\[^WzPŋ9ЈΈΈVȈFDpfDQ"rFD3"?Gr b_DW("3"2!""3"2Q"*@DpFDF4"RiFFDN3"3"RlDgFM|zվ>F. D^`;HN8IENDB`./library_c/unicorn/anim/hypnotoad.png0000664000175000017500000000207714223621661021234 0ustar jawn-smithjawn-smithPNG  IHDR tEXtSoftwareAdobe ImageReadyqe<&iTXtXML:com.adobe.xmp IDATxڴR9! G4/wкCJIqM#1!LŒ{+Ggtm")ڢm S*刦W"h-Y!h|_oyIENDB`./library_c/unicorn/anim/rainbowspin.png0000664000175000017500000001131414223621661021554 0ustar jawn-smithjawn-smithPNG  IHDRZ7htEXtSoftwareAdobe ImageReadyqe<&iTXtXML:com.adobe.xmp y`qX0-pُI?h]EyЎ >.G۵ n]`0ͽ/EG|Ro |»%/A _DzL9at%C0D>*U _ wct J(X"?}y)N.G+:MDu`._ւ]fHupXZ@?=CX[$#w %VGUI?@-ڄID?u0Pȝnxg6q~3;6Δ(=n`8e9{}AU ˼yRqA} io sdCnUH HUϭ{^\/>Իm[;y{4WxD'0G_ 4 }Mт  j;?ro4jWͳ5NU*rEsI' bƱp_3%gN@Xҕ, Ҡ}ia.E_)$|zQ$7b2$2T#EN^גу6mI!PݴN Q|dFPy!S"%bS(q)rYL]xڮvA>K4A.PwL۴uP Ylں* diY nPQT>*2tqdllߝKyC'Kx,+HIcKAm>C&fM2^WAleϬ)730 T}cDHCICVBGۛޡ{ 1vΔOVi?2DDzUZY\Yvi&RĦ5:,Sx,8M5j9 1Zg0K{c.Rv?#l9Jc§Yzj4hџ[@vK vsz{8ƫR G+l3)VJLU96$>"֯h#A=qy)56̱X &dn`c7zOG'OZ^k2>B9:l+\,2>Ƚ~)/R!P iSe}S)BkCىYT0,=I[%1f<JtT}⼹vj!'3vyozմiHSCh}PIj̲ei!1É%k|zb)fZ43%.iS>?jbNr?ӨQG>a9\nw6iH;cW&̖^Q&Sm5N SW:.X5E㆔!ghbdQ*y̓:j#IlڼN/TаHꊙE֥9z4ZgN'i..s  xt\T[j(dU?pȏa>M4ٽ6xMިRM#4]nf.r.QF_<UcZ&fr}22ς yn7g,@Gi!P5ξRcm:2dus3 ~Dwj#pqy%g _27xI5ک,EKQ"'M4 iЄ4tQ6nV3Ȭ^q0&}` 8&> uq,@F*Ȳ2ZeE֡ 6BJo$cȺC9jȘҽǙ[K6mLU(VF.^fhӜ#U f)Vj++iwxvzZVdl Bm_ָb޸|Ĉ4b fW] HiM£WX"SI/ #8(ERwMW*gK`˼_rӴ:,pE[=[mTpq wUHe:ohs5-z7Syn5bB]e^ ;\{?ud-dO"/@)-Cf;3Qʵt&ewTMAx碿L?M3jݒʆw ۓwn7vf}/aXR>m jIDATxTMD0e%A~b+K>``\ ͤ13k_?_גiVU%]@qY\Jeu]m_u]8b'6p`xA-lEBD]Gr$ٲEQ i+˲0m6M#9 c}Hg4m*l>0,NGru]_'cWwc&yޑ 02B5]IENDB`./library_c/unicorn/anim/off.png0000664000175000017500000000163614223621661020001 0ustar jawn-smithjawn-smithPNG  IHDRKm)tEXtSoftwareAdobe ImageReadyqe<&iTXtXML:com.adobe.xmp 0IDATxb` 76IENDB`./library_c/unicorn/anim/boom.png0000664000175000017500000000410714223621661020157 0ustar jawn-smithjawn-smithPNG  IHDRx@O$tEXtSoftwareAdobe ImageReadyqe<&iTXtXML:com.adobe.xmp D cIDATxOhU?/+1l6*mGZ؃ ԃ"Hnc!xңQ*-OBmZJԦnim7iO<8Y~yofwͼRV^1ݭ )KL-}:7efx84 vs=A5MCz'73 h:Z\b5<6 ['L/OiAABnÉ4AfJ f#e+d1%/:ۜPGۙn 0Vo]j#;TCd'n0a1),VtU4ԏ[X!Ƹ:I[ƥ1@$IDHt5HOm Ks2=FxOF ,)zBoCb4CNmy["Ì8L p8fF~\/Q9$r)x4d#d=W9܂KpΛ8l\"W9w쩅dRS;4*Y7+Kz䃙4f3Ɨwk(/,qa/޽JQ z%|Ņ˾ OX; n^]sc|se#3CX}‡\.Oޞ8 |\8p>?5Yz$j|wٿW9zy_vUgE DpXWӽ=K+~W~]w|'<$_,ogIHGu=1Xnzq)J Y}nn)L\ ㌰⣭D'}F}4wnP׳,gUKƝv4Ewv5儋7 ;1YG5zo]&cZi=z4>1:N ܩ׵F}uU.V,`ԝcpSY+Xn"PIH^W Ae.nz`AsYYµZ5333a}{tl8)Z 9F$DuHq0ʊI15ҥʠU|!Pm[zzSh)(|w)v %Rf[*[Zyw5--fˍ PQ.ԎEШ6|s\q,DsΆgbSݖ ƒH5qd̴'^ŵ M*[͖kHmoU%ĹqIENDB`./library_c/unicorn/anim/rainbow.png0000664000175000017500000000322114223621661020660 0ustar jawn-smithjawn-smithPNG  IHDRitEXtSoftwareAdobe ImageReadyqe<&iTXtXML:com.adobe.xmp YBIDATxtMnA ݶ""@l9l0$g5\Lx~N䨩77l5u6 >`-(/ v~Xv#93s]F0AUe̶]:Q`G73pSVn(>\-ʝWLhҢY>AzXkVPM5:2ejW%1Bf|i^`Zs zG[:Da5qH-U4-a1DbCHbhԴB-h1D!$Z !bc@9 !b#ibKZ CH- h1D۵X,h1!$Z !bCňZ\#-F Y !bhBG08q`.0d1DѝaC-h1Z9 =h1D!$Z !bCHB=-h14rZ,FCH5-*1d1D!$Z !bCH]ch4CHBPJbCŴqb!$Z !b蠴B-h1D!$!$Z !bqG  F tIDATxA Ey5ʑFsѢ*4xӶ2ud$$0k)4&,f[M0cDz !p{B>6P>Dw"Tf'WM!3۸}eF9cߔFn:Pݻ/3E}۸?.*TNBr\IENDB`./library_c/unicorn/unicorn.c0000664000175000017500000002262014223621661017412 0ustar jawn-smithjawn-smith#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ws2811.h" #define TARGET_FREQ WS2811_TARGET_FREQ #define GPIO_PIN 18 #define DMA 5 #define WIDTH 8 #define HEIGHT 8 #define LED_COUNT (WIDTH * HEIGHT) ws2811_t ledstring = { .freq = TARGET_FREQ, .dmanum = DMA, .channel = { [0] = { .gpionum = GPIO_PIN, .count = LED_COUNT, .invert = 0, .brightness = 55, .strip_type = WS2811_STRIP_GRB, } } }; void setBrightness(int b) { ledstring.channel[0].brightness = b; return; } void setPixelColorRGB(int pixel, int r, int g, int b) { ledstring.channel[0].leds[pixel] = (r << 16) | (g << 8) | b; return; } void clearLEDBuffer(void){ int i; for(i=0; i 1.0){ h=fabsf(fmodf(h,1.0)); } h *= 360.0; h /= 60.0; i = floor( h ); f = h - i; p = (v * ( 1 - s )); q = (v * ( 1 - s * f )); t = (v * ( 1 - s * ( 1 - f ) )); switch( i ){ case 0: *r = v; *g = t; *b = p; break; case 1: *r = q; *g = v; *b = p; break; case 2: *r = p; *g = v; *b = t; break; case 3: *r = p; *g = q; *b = v; break; case 4: *r = t; *g = p; *b = v; break; default: *r = v; *g = p; *b = q; break; } } void makeRGB(float *r, float *g, float *b, float f1, float f2, float f3, float p1, float p2, float p3, float c, float w, float pos){ *r = (( sin(f1 * pos + p1) * w ) + c) / 255; *g = (( sin(f2 * pos + p2) * w ) + c) / 255; *b = (( sin(f3 * pos + p3) * w ) + c) / 255; } void transformPixel(float *x, float *y, float angle){ float px, py, cs, sn; cs = cos(angle); sn = sin(angle); px = *x * cs - *y * sn; py = *x * sn + *y * cs; *x = px; *y = py; } void shadePixel(double t, int pixel, float x, float y){ float r, g, b; float angle = fmod( (double)(t)/10, (double)360); angle /= 57.2957795; float px, py, cs, sn; // Move origin to center x-=0.5; y-=0.5; // Pan the X/Y position on a sine wave x+=sin(t/10000.0); y+=sin(y/10000.0); // Rotate the pixels cs = cos(angle); sn = sin(angle); px = (x * cs) - (y * sn); py = (y * cs) + (x * sn); // Convert hue to RGB float hue = (((px+py)/8) + t / 10000.0); h2rgb(hue, &r, &g, &b); // Clamp max value if(r>1.0) r=1.0; if(g>1.0) g=1.0; if(b>1.0) b=1.0; setPixelColorRGB(pixel, (int)(r*255), (int)(g*255), (int)(b*255)); } /* Loop through every pixel in the display and call shadePixel with its coordinates, its index and the current time vector. */ void run_shader(void){ struct timeval tv; double t; while(1){ gettimeofday(&tv, NULL); t = (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000; for(y=0; y<8; y++){ for(x=0; x<8; x++){ int pixel = getPixelPosition(x,y); shadePixel(t, pixel, x/7.0, y/7.0); } } show(); usleep(1); } } /* Clear the display and exit gracefully */ void unicorn_exit(int status){ int i; for (i = 0; i < 64; i++){ setPixelColorRGB(i,0,0,0); } ws2811_render(&ledstring); ws2811_fini(&ledstring); exit(status); } int main(int argc, char **argv) { int shader = 0; if (argc >= 3){ if(sscanf (argv[2], "%i", &anim_delay)!=1){ printf ("Error, delay must be an integer \n"); return 0; } } int newbrightness = 0; if (argc >= 4){ if(sscanf (argv[3], "%i", &newbrightness)!=1){ printf ("Error, brightness must be an integer \n"); return 0; }else{ setBrightness(newbrightness); } } if (argc == 2){ if(sscanf (argv[1], "%i", &newbrightness)==1){ setBrightness(newbrightness); shader = 1; } } /* All terminating signals, as described by 'man 7 signal'. */ static const int term_signals[] = { /* POSIX.1-1990 */ SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGKILL, SIGSEGV, SIGPIPE, SIGALRM, SIGTERM, SIGUSR1, SIGUSR2, /* POSIX.1-2001 */ SIGBUS, SIGPOLL, SIGPROF, SIGSYS, SIGTRAP, SIGVTALRM, SIGXCPU, SIGXFSZ, }; int i; for (i = 0; i < sizeof(term_signals)/sizeof(term_signals[0]); i++) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = unicorn_exit; sigaction(term_signals[i], &sa, NULL); } setvbuf(stdout, NULL, _IONBF, 0); if(ws2811_init(&ledstring)) { return -1; } clearLEDBuffer(); if(argc < 2){ shader = 1; } if(shader){ run_shader(); }else{ read_png_file(argv[1]); while(1){ process_file(); if (height/8 == 1){ break; } } } unicorn_exit(0); return 0; } ./library_c/unicorn/.gitignore0000664000175000017500000000001014223621661017546 0ustar jawn-smithjawn-smithunicorn ./library_c/unicornd/0000775000175000017500000000000014223621661015733 5ustar jawn-smithjawn-smith./library_c/unicornd/unicorn0000664000175000017500000000212714223621661017335 0ustar jawn-smithjawn-smith#!/bin/sh ### BEGIN INIT INFO # Provides: unicorn # Required-Start: $network $syslog # Required-Stop: $network $syslog # Default-Start: 2 3 4 5 # Default-Stop: # Short-Description: Start Unicorn hat daemon ### END INIT INFO PATH=/sbin:/bin:/usr/sbin:/usr/bin . /lib/lsb/init-functions DAEMON=/usr/sbin/unicornd PIDFILE=/var/run/unicornd.pid test -x $DAEMON || exit 5 case $1 in start) log_daemon_msg "Starting Unicorn Hat server" "unicornd" start-stop-daemon --start -b --quiet --oknodo --pidfile $PIDFILE -m --startas $DAEMON -- $UNICORND_OPTS status=$? log_end_msg $status ;; stop) log_daemon_msg "Stopping Unicorn Hat server" "unicornd" start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE log_end_msg $? rm -f $PIDFILE ;; restart|force-reload) $0 stop && sleep 2 && $0 start ;; try-restart) if $0 status >/dev/null; then $0 restart else exit 0 fi ;; reload) exit 3 ;; status) status_of_proc $DAEMON "Unicorn Hat server" ;; *) echo "Usage: $0 {start|stop|restart|try-restart|force-reload|status}" exit 2 ;; esac ./library_c/unicornd/build.sh0000775000175000017500000000014014223621661017364 0ustar jawn-smithjawn-smith#!/bin/bash git submodule update --init sudo apt install scons cd rpi_ws281x scons cd ../ make ./library_c/unicornd/test_client/0000775000175000017500000000000014223621661020250 5ustar jawn-smithjawn-smith./library_c/unicornd/test_client/unicorn_demo3.py0000664000175000017500000000273614223621661023376 0ustar jawn-smithjawn-smith#!/usr/bin/python import socket import struct from random import randint from time import sleep socket_path = "/var/run/unicornd.socket" class Unicorn: flag_lumen = bytes([0]) flag_set_px = bytes([1]) flag_set_all_px = bytes([2]) flag_show = bytes([3]) def __init__(self): self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) def connect(self): self.sock.connect(socket_path) def set_brightness(self, val): self.sock.send(struct.pack('=cc', self.flag_lumen, bytes([val]))) def set_pixel(self, x, y, r, g, b): self.sock.send(self.flag_set_px + bytes([x, y, r, g, b])) def clear(self): self.set_all_pixels(0, 0, 0) def set_all_pixels(self, r, g, b): self.sock.send(self.flag_set_all_px + bytes([r, g, b] * 64)) def show(self): self.sock.send(struct.pack('=c', self.flag_show)) class UnicornDemo: def __init__(self, unicorn): self.unicorn = unicorn def show_random(self): for i in range(100): x = randint(0, 7) y = randint(0, 7) r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) self.unicorn.set_pixel(x, y, r, g, b) self.unicorn.show() sleep(0.1) def main(): u = Unicorn() u.connect() u.set_brightness(20) u.clear() demo = UnicornDemo(u) #demo.show_random() u.clear() u.show() if __name__ == "__main__": main() ./library_c/unicornd/test_client/Unicorn.pm0000664000175000017500000000221214223621661022220 0ustar jawn-smithjawn-smithpackage Unicorn; use strict; use warnings; use IO::Socket::UNIX; my $UNICORND_SOCKET_PATH = "/var/run/unicornd.socket"; my $UNICORND_CMD_SET_BRIGHTNESS = 0; my $UNICORND_CMD_SET_PIXEL = 1; my $UNICORND_CMD_SET_ALL_PIXELS = 2; my $UNICORND_CMD_SHOW = 3; sub set_all_pixels { my $self = shift; my $command = pack "C*", $UNICORND_CMD_SET_ALL_PIXELS, @_; $self->{socket}->send($command); } sub clear { my $self = shift; $self->set_all_pixels((0,0,0) x 64); } sub set_pixel { my $self = shift; my $command = pack "CCCCCC", $UNICORND_CMD_SET_PIXEL, @_; $self->{socket}->send($command); } sub show { my $self = shift; my $command = pack "C", $UNICORND_CMD_SHOW; $self->{socket}->send($command); } sub set_brightness { my $self = shift; my $brightness = shift; my $command = pack "CC", $UNICORND_CMD_SET_BRIGHTNESS, $brightness; $self->{socket}->send($command); } sub new { my ($class) = @_; my $socket = IO::Socket::UNIX->new( Peer => $UNICORND_SOCKET_PATH, Type => SOCK_STREAM(), ); return bless { socket => $socket, }, $class; } 1; ./library_c/unicornd/test_client/unicorn_demo.py0000664000175000017500000000036214223621661023304 0ustar jawn-smithjawn-smithimport client as u from random import randint u.connect() u.clear() while True: x = randint(0, 7) y = randint(0, 7) r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) u.set_pixel(x, y, r, g, b) u.show() ./library_c/unicornd/test_client/client.rb0000664000175000017500000000203214223621661022050 0ustar jawn-smithjawn-smith#!/usr/bin/ruby # # Copyright (C) 2014 jibi # require 'socket' UNICORND_SOCKET_PATH = "/var/run/unicornd.socket" UNICORND_CMD_SET_BRIGHTNESS = 0 UNICORND_CMD_SET_PIXEL = 1 UNICORND_CMD_SET_ALL_PIXELS = 2 UNICORND_CMD_SHOW = 3 def connect $sock = UNIXSocket.new(UNICORND_SOCKET_PATH) end def set_brightness(val) $sock.write([UNICORND_CMD_SET_BRIGHTNESS, val].pack("CC")) end def set_pixel(x,y,r,g,b) $sock.write([UNICORND_CMD_SET_PIXEL, x, y, r, g, b].pack("CCCCCC")) end def set_all_pixels(pixels) $sock.write([UNICORND_CMD_SET_ALL_PIXELS, pixels].flatten.pack("C*")) end def show $sock.write([UNICORND_CMD_SHOW].pack("C")) end connect set_brightness(40) set_pixel(2,2, 255, 0, 0) set_pixel(4,4, 0, 255, 0) set_pixel(6,6, 0, 0, 255) show sleep(2) pixels = [] 8.times do |x| 8.times do |y| z = (x + y) % 3 case z when 0 pixels << [255,0,0] when 1 pixels << [0,255,0] when 2 pixels << [0,0,255] end end end set_all_pixels(pixels) show ./library_c/unicornd/test_client/client.py0000664000175000017500000000177114223621661022106 0ustar jawn-smithjawn-smith#!/usr/bin/env python import socket, struct, atexit UNICORND_SOCKET_PATH = "/var/run/unicornd.socket" UNICORND_CMD_SET_BRIGHTNESS = 0 UNICORND_CMD_SET_PIXEL = 1 UNICORND_CMD_SET_ALL_PIXELS = 2 UNICORND_CMD_SHOW = 3 UNICORND_CMD_CLEAR = 4 sock = None def connect(): global sock sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(UNICORND_SOCKET_PATH) atexit.register(close) def set_brightness(val): sock.send(struct.pack('=cc',*[chr(UNICORND_CMD_SET_BRIGHTNESS), val])) def set_pixel(x,y,r,g,b): sock.send(''.join(chr(x) for x in [UNICORND_CMD_SET_PIXEL, x, y, r, g, b])) def clear(): sock.send(struct.pack('=c',chr(UNICORND_CMD_CLEAR))) def set_all_pixels(pixels): sock.send(chr(UNICORND_CMD_SET_ALL_PIXELS) + ''.join(chr(x) for x in pixels)) def show(): sock.send(struct.pack('=c',chr(UNICORND_CMD_SHOW))) def close(): global sock if sock: clear() show() sock.close() sock = None./library_c/unicornd/test_client/unicorn_demo.pl0000664000175000017500000000115214223621661023265 0ustar jawn-smithjawn-smith#!/usr/bin/perl use strict; use warnings; use Unicorn; my $u = Unicorn->new(); $u->set_brightness(20); $u->clear(); $u->set_pixel(2, 2, 255, 0, 0); $u->set_pixel(4, 4, 0, 255, 0); $u->set_pixel(6, 6, 0, 0, 255); $u->show; sleep(3); my @pixels; for my $x (1..8) { for my $y (1..8) { my $z = ($x + $y) % 3; if($z == 0) { push @pixels, (255, 0, 0); } elsif($z == 1) { push @pixels, (0, 255, 0); } elsif($z == 2) { push @pixels, (0, 0, 255); } } } $u->set_all_pixels(@pixels); $u->show; #sleep(6); #$u->clear; #$u->show; ./library_c/unicornd/unicornd.service0000664000175000017500000000016414223621661021137 0ustar jawn-smithjawn-smith[Unit] Description=Unicorn HAT daemon [Service] ExecStart=/usr/sbin/unicornd [Install] WantedBy=multi-user.target ./library_c/unicornd/unicornd.c0000664000175000017500000001341014223621661017717 0ustar jawn-smithjawn-smith/* * Copyright (C) 2014 jibi * */ #include #include #include #include #include #include #include #include #include #include #include #include "ws2811.h" #define TARGET_FREQ WS2811_TARGET_FREQ #define GPIO_PIN 18 #define DMA 10 #define WIDTH 8 #define HEIGHT 8 #define LED_COUNT (WIDTH * HEIGHT) ws2811_t ledstring = { .freq = TARGET_FREQ, .dmanum = DMA, .channel = { [0] = { .gpionum = GPIO_PIN, .count = LED_COUNT, .invert = 0, .brightness = 55, .strip_type = WS2811_STRIP_GRB, } } }; static inline int get_pixel_pos(uint8_t x, uint8_t y) { int map[8][8] = { {7 ,6 ,5 ,4 ,3 ,2 ,1 ,0 }, {8 ,9 ,10,11,12,13,14,15}, {23,22,21,20,19,18,17,16}, {24,25,26,27,28,29,30,31}, {39,38,37,36,35,34,33,32}, {40,41,42,43,44,45,46,47}, {55,54,53,52,51,50,49,48}, {56,57,58,59,60,61,62,63} }; return map[x][y]; } static inline void set_pixel_color(int pixel, int r, int g, int b) { ledstring.channel[0].leds[pixel] = (r << 16) | (g << 8) | b; } static inline void clear_led_buffer(void) { int i; for(i = 0; i < LED_COUNT; i++){ set_pixel_color(i, 0, 0, 0); } } static inline void set_brightness(int b) { ledstring.channel[0].brightness = b; } static inline void show(){ ws2811_render(&ledstring); } static inline void unicornd_exit(int status) { clear_led_buffer(); show(); ws2811_fini(&ledstring); exit(status); } static inline void init_unicorn_hat(void) { int i; struct sigaction sa; /* All terminating signals, as described by 'man 7 signal'. */ static const int term_signals[] = { /* POSIX.1-1990 */ SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGKILL, SIGSEGV, SIGPIPE, SIGALRM, SIGTERM, SIGUSR1, SIGUSR2, /* POSIX.1-2001 */ SIGBUS, SIGPOLL, SIGPROF, SIGSYS, SIGTRAP, SIGVTALRM, SIGXCPU, SIGXFSZ, }; for (i = 0; i < sizeof(term_signals)/sizeof(term_signals[0]); i++) { memset(&sa, 0, sizeof(sa)); sa.sa_handler = unicornd_exit; sigaction(term_signals[i], &sa, NULL); } setvbuf(stdout, NULL, _IONBF, 0); if (ws2811_init(&ledstring) < 0) { exit(1); } clear_led_buffer(); set_brightness(20); } #define SOCK_PATH "/var/run/unicornd.socket" #define UNICORND_CMD_SET_BRIGHTNESS 0 #define UNICORND_CMD_SET_PIXEL 1 #define UNICORND_CMD_SET_ALL_PIXELS 2 #define UNICORND_CMD_SHOW 3 #define UNICORND_CMD_CLEAR 4 #define recv_or_return(socket, buf, len, flags) \ { \ int _ret; \ _ret = recv(socket, buf, len, flags); \ \ if (_ret <= 0) { \ close(socket); \ return; \ } \ } typedef struct col_s { uint8_t r; uint8_t g; uint8_t b; } col_t; typedef struct pos_s { uint8_t x; uint8_t y; } pos_t; static int setup_listen_socket(void) { int listen_socket; int ret; socklen_t len; struct sockaddr_un local; listen_socket = socket(AF_UNIX, SOCK_STREAM, 0); if (listen_socket == -1) { fprintf(stderr, "cannot create unix socket"); exit(1); } unlink(SOCK_PATH); local.sun_family = AF_UNIX; strcpy(local.sun_path, SOCK_PATH); len = strlen(local.sun_path) + sizeof(local.sun_family); ret = bind(listen_socket, (struct sockaddr *) &local, len); if (ret == -1) { fprintf(stderr, "cannot bind socket"); exit(1); } chmod(SOCK_PATH, 0777); ret = listen(listen_socket, 4); if (ret == -1) { fprintf(stderr, "cannot listen on socket"); exit(1); } return listen_socket; } static int do_accept(int listen_socket) { struct sockaddr_un client; int client_socket; socklen_t len; len = sizeof(client); client_socket = accept(listen_socket, (struct sockaddr *)&client, &len); if (client_socket == -1) { fprintf(stderr, "cannot accept client connection"); exit(1); } return client_socket; } static void handle_client(int client_socket) { uint8_t cmd; char bright; pos_t pos; col_t col; col_t pixels[64]; int x, y; while (true) { recv_or_return(client_socket, &cmd, sizeof(char), 0); switch (cmd) { case UNICORND_CMD_SET_BRIGHTNESS: recv_or_return(client_socket, &bright, sizeof(char), 0); set_brightness(bright); break; case UNICORND_CMD_SET_PIXEL: recv_or_return(client_socket, &pos, sizeof(pos_t), 0); recv_or_return(client_socket, &col, sizeof(col_t), 0); set_pixel_color(get_pixel_pos(pos.x, pos.y), col.r, col.g, col.b); break; case UNICORND_CMD_SET_ALL_PIXELS: recv_or_return(client_socket, &pixels, 64 * sizeof(col_t), 0); for (x = 0; x < 8; x++) { for (y = 0; y < 8; y++) { col_t *col = &pixels[x * 8 + y]; set_pixel_color(get_pixel_pos(x, y), col->r, col->g, col->b); } } break; case UNICORND_CMD_SHOW: show(); break; case UNICORND_CMD_CLEAR: clear_led_buffer(); break; default: close(client_socket); return; } } } int main(void) { int listen_socket, client_socket; init_unicorn_hat(); listen_socket = setup_listen_socket(); while (true) { client_socket = do_accept(listen_socket); if (client_socket != -1) { handle_client(client_socket); } } return 0; } ./library_c/unicornd/Makefile0000664000175000017500000000076414223621661017402 0ustar jawn-smithjawn-smith.PHONY: all clean install install-archlinux ws281x_path = rpi_ws281x all: unicornd $(ws281x_path)/libws2811.a: scons -C $(ws281x_path) unicornd: unicornd.c $(ws281x_path)/libws2811.a gcc -Wall unicornd.c -o unicornd -I$(ws281x_path) -L$(ws281x_path) -lws2811 clean: scons -C $(ws281x_path) --clean -rm -f unicornd install: cp unicornd /usr/sbin cp unicorn /etc/init.d sudo chmod +x /etc/init.d/unicorn install-archlinux: cp unicornd /usr/sbin cp unicornd.service /etc/systemd/system/ ./library_c/unicornd/.gitignore0000664000175000017500000000001114223621661017713 0ustar jawn-smithjawn-smithunicornd ./library_c/unicornd/README.md0000664000175000017500000000501614223621661017214 0ustar jawn-smithjawn-smithUnicorn Hat daemon ===================== Unicorn Hat daemon is a simple C program that listen on a Unix socket in `/var/run/unicornd.socket` and accepts command to set the leds of the Unicorn Hat so that you can run the daemon as root and your programs as normal user. It can handle only one connection at a time and since the socket has `0777` mode every user can connect to the socket. ### Building Run `./build.sh` to clone and build the rpi_ws281x library and this daemon. Otherwise make sure you have scons installed, initalize the submodule directory and build manually: ``` sudo apt install scons git submodule update --init cd rpi_ws281x scons build # If scons build fails, try scons without the build argument cd ../ make ``` ### Installation #### Raspbian `make install` will install the daemon ``` make sudo make install sudo service unicorn start sudo service unicorn stop ``` To set the daemon to start at boot run `sudo update-rc.d unicorn defaults` If you see an error like this, ``` [....] Starting unicorn (via systemctl): unicorn.serviceFailed to start unicorn.service: Unit unicorn.service failed to load: No such file or directory. ``` This is because you are running systemd on the new debian and the new sysv/systemd compatibility shim hasn't run. Running it manually will generate the necessary service file. This will be put in /tmp. This process normally happens on startup so you aren't likely to need to do it again. ``` sudo /lib/systemd/system-generators/systemd-sysv-generator sudo service unicorn start ``` #### Arch Linux ARM `make install-archlinux` will install the daemon ``` make su make install-archlinux systemctl start unicornd systemctl stop unicornd ``` To set the daemon to start at boot run `systemctl enable unicornd` ### Protocol The protocol is simple: each command is composed of a code (the command you want to execute) and its possible arguments. You need to first connect to the Unix socket and the send a struct that describe the command. ##### set brightness ```c struct { uint8_t code; // set to 0 double val; }; ``` ##### set pixel ```c struct { uint8_t code; // set to 1 pos_t pos; col_t col; }; ``` where `pos_t` is a struct like this: ```c struct { uint8_t x; uint8_t y; }; ``` and where `col_t` is a struct like this: ```c struct { uint8_t r; uint8_t g; uint8_t b; }; ``` ##### set all pixels ```c struct { uint8_t code; // set to 2 col_t pixels[64]; }; ``` ##### show ```c struct { uint8_t code; // set to 3 }; ``` ### examples See the Ruby and Perl test clients ./library_c/unicornd/rpi_ws281x/0000775000175000017500000000000014223621661017661 5ustar jawn-smithjawn-smith./library_c/Makefile0000664000175000017500000000027214223621661015553 0ustar jawn-smithjawn-smith.PHONY: clean unicornd unicorn all: unicornd unicorn unicornd: make -C unicornd/ unicornd unicorn: make -C unicorn/ unicorn clean: make -C unicornd/ clean make -C unicorn/ clean ./README.md0000664000175000017500000000627214223621661013432 0ustar jawn-smithjawn-smith![Unicorn HAT/pHAT](unicorn-hat-logo.png) Available from Pimoroni: http://shop.pimoroni.com/products/unicorn-hat http://shop.pimoroni.com/products/unicorn-phat ### Important Notice Because Unicorn HAT uses the PWM hardware, which is also how your Raspberry Pi generates analog audio, you may see random colour patterns and flickering. If this happens, you should add the following to your `/boot/config.txt`: ``` hdmi_force_hotplug=1 ``` Sound will work fine using speakers on, for example, an HDMI TV, but you will not be able to use your Pi's 3.5mm audio jack in conjunction with Unicorn HAT. ### `unicornhat` Python Library & Examples Here you'll find everything you need to start lighting up your Unicorn HAT or pHAT using python. Python users should probably ignore most of this repository and just: **Full install ( recommended ):** ```bash curl -sS https://get.pimoroni.com/unicornhat | bash ``` **Install for Python 3:** ```bash sudo apt-get install python3-pip python3-dev sudo pip3 install unicornhat ``` **Install for Python 2:** ```bash sudo apt-get install python-pip python-dev sudo pip install unicornhat ``` **Install from GitHub** Note this library requires the rpi_ws281x Python library which you can find here: https://github.com/pimoroni/rpi_ws281x-python ``` git clone https://github.com/pimoroni/unicorn-hat cd unicorn-hat/library/UnicornHat sudo python setup.py install cd ../.. ``` Then proceed to [examples](examples). ### Using with idle/idle3: `unicornhat` needs root access to function. Please make sure you start LXTerminal and run idle or idle3 with the "sudo" command like so: ```bash sudo idle ``` ### Error Codes Sometimes Unicorn HAT may fail with an error code, this table details some of the places to look for answers in specific cases: * -1 Generic failure * -2 Out of memory * -3 Hardware revision is not supported - **see: https://github.com/pimoroni/unicorn-hat/issues/70** * -4 Memory lock failed * -5 mmap() failed - **you probably forgot to run your code as root, use `sudo python yourcode.py`** * -6 Unable to map registers into userspace * -7 Unable to initialize GPIO * -8 Unable to initialize PWM" * -9 Failed to create mailbox device * -10 DMA error * -11 Selected GPIO not possible * -12 Unable to initialize PCM * -13 Unable to initialize SPI * -14 SPI transfer error ### Documentation & Support * Getting started - https://learn.pimoroni.com/tutorial/unicorn-hat/getting-started-with-unicorn-hat * Function reference - http://docs.pimoroni.com/unicornhat/ * GPIO Pinout - http://pinout.xyz/pinout/unicorn_hat, http://pinout.xyz/pinout/unicorn_phat * Get help - http://forums.pimoroni.com/c/support ### Based Upon rpi_ws281x `unicornhat` is based upon a modified, Pi 2/3 compatible version of the RPi ws281x Library by Jeremy Garff. The library was modified by Richard Hirst. * Modified version: https://github.com/richardghirst/rpi_ws281x * Original: https://github.com/jgarff/rpi_ws281x ### RaspberryPi-NeoPixel-WS2812 Note: `unicornhat` is no longer based upon this library, but this information is included for posterity. `unicornhat` was previously based upon a modified version of the ws2812 C driver from: https://github.com/626Pilot/RaspberryPi-NeoPixel-WS2812 ./examples/0000775000175000017500000000000014223621661013762 5ustar jawn-smithjawn-smith./examples/binary_clock.py0000775000175000017500000001355614223621661017010 0ustar jawn-smithjawn-smith#!/usr/bin/env python from __future__ import print_function import unicornhat import datetime from time import sleep print("""True Binary Clock made by Jarrod Price, inspired by Iorga Dragos Florian and reviewed by Philip Howard Displays the time on the LEDs as follows: Top row -> First 4 = Month(Pink), Last 4 = Day(Blue/Green. If Green add 16 to value shown, no lights = 16th) Second row -> First 2 = Alarm(Orange), Last 6 = Hour(Red) Third row -> First 2 = Alarm(Orange), Last 6 = Minute(Yellow) Fourth row -> First 2 = Alarm(Orange), Last 6 = Second(Green)""") unicornhat.set_layout(unicornhat.AUTO) # default brightness does not need to be too bright unicornhat.brightness(0.5) # get the width of the hat because the LEDs are displayed from the righ to the left width, height = unicornhat.get_shape() right_most_pixel = width - 1 # colour tuples red = (255, 0, 0) orange = (255, 127, 0) yellow = (255, 255, 0) green = (0, 255, 0) blue = (0, 127, 255) lightblue = (100, 200, 255) magenta = (255, 0, 255) white = (255, 255, 255) # alarm must be 24 hour format alarm_time = '07:00' # how many minutes should the alarm flash for alarm_flash_time = 5 # inform the world what time the alarm will go off print('Alarm set for: ', alarm_time) def draw_time_string(time_string, length, offset, row, colour): """Draw the binary time on a specified row in a certain colour. :param time_string: string containing time value that will be used for the bit comparison :param length: width of the binary string once converted, e.g. 5 bits for day, 6 bits for hour and minute :param offset: left offset - all values are displayed with right alignment as conventional binary dictates, the offest will move it to the left :param row: row on which to display the time, this is the y-axis :param colour: colour to draw in """ # convert the time string to an integer value = int(time_string) # loop through the pixels from the right to the left for i in range(right_most_pixel, right_most_pixel - length, -1): # use the & operator to do a bit comparison # for example: # 1 & 1 = 1 (ie: 0b1 & 0b1 = 0b1) # 2 & 1 = 0 (ie: 0b10 & 0b01 = 0b00) if value & 1: rgb = colour else: rgb = (0, 0, 0) # determine where on the row it should display this LED # either at the given location in the loop or shifted over to the left a little column = (i - offset) # set the pixels colour unicornhat.set_pixel(column, row, rgb) # use a binary shift to move all the values over to the right # for example: # 10 = 0b1010 shifted by 1 place becomes 0b0101 = 5 # 5 = 0b101 shifted by place becomes 0b010 = 2 value >>= 1 # this function will make use of the remaining space to light up when indicated def alarm(t, c): # by default we will assume the alarm will not be triggered so keep the default states of the brightness and LED colours unicornhat.brightness(0.5) b = '0' # grab the hour and minute from the set alarm time h = int(alarm_time[:2]) m = int(alarm_time[3:]) s = 0 # create time slot for alarm for today at = t.replace(hour=h, minute=m, second=s) # create a new time object by adding x minutes to the alarm time ft = at + datetime.timedelta(minutes=alarm_flash_time) # now check if it's time to flash the alarm or not, by checking if we have passed the time it is meant to go off or 5 minutes have not gone passed if t >= at and t < ft: # signal the alarm! # set the brightness to max unicornhat.brightness(1) # this will make it flash ON when a second is equal and OFF when it is odd if int(t.second % 2) == 0: # when converted to binary becomes 0b11, so this will turn ON 2 LEDs per row b = '3' # always update the pixels, the logic above will decide if it displays or not # 3 rows, 2 LEDs wide for the alarm, padded to left by 6 draw_time_string(b, 2, 6, 1, c) draw_time_string(b, 2, 6, 2, c) draw_time_string(b, 2, 6, 3, c) # this is the main function, will get the current time and display each time and check the alarm def binary_clock(): try: while True: now = datetime.datetime.now() # draw each time string in their specific locations draw_time_string(now.month, 4, 4, 0, magenta) # Day field is 4 bits (lights) long, and as we don't use 0-indexed # days of the month, that means we can only represent 1-15 (0b1 - 0b1111) # To solve this, if the day > 15 (0b1111), we change the colour to indidcate # that 16 (0b10000) must be added to the displayed value. if now.day > 0b1111: # Day > 15 # Truncate the day to only 4 bits, as we only have 4 lights # This will remove the bit representing 16, which will # be encoded as colour day = now.day & 0b1111 # Encode the missing bit as colour day_colour = green else: # Day is 15 or less so the bit representing 16 is not set and the number can be displayed normally day = now.day day_colour = blue draw_time_string(day, 4, 0, 0, day_colour) draw_time_string(now.hour, 6, 0, 1, red) draw_time_string(now.minute, 6, 0, 2, yellow) draw_time_string(now.second, 6, 0, 3, green) # check if the alarm needs to be signalled or not alarm(now, orange) # we've now set all the LEDs, time to show the world our glory! unicornhat.show() # sleep for 1 second, because we don't want to waste unnecessary CPU sleep(1) except Exception as e: print(e) print("Exiting") if __name__ == "__main__": binary_clock() ./examples/detect.py0000775000175000017500000000241414223621661015610 0ustar jawn-smithjawn-smith#!/usr/bin/env python print("""Unicorn HAT Detect-o-matic v2.0 Note: Your Unicorn HAT must be plugged in before boot to detect properly! """) product = None try: product = open("/proc/device-tree/hat/product","r").read().strip().replace("\x00", "") except IOError: pass if product is None: print( """We couldn't find a connected EEPROM, so we'll assume you're using a Unicorn pHAT. You should use the following in your code: import unicornhat unicornhat.set_layout(unicornhat.PHAT) If you're sure you've connected a HAT, use: import unicornhat unicornhat.set_layout(unicornhat.HAT) """) else: if product[:11] == "unicornhat": print( """We found a Unicorn HAT connected to your Pi. You should use the following in your code: import unicornhat unicornhat.set_layout(unicornhat.HAT) """) else: print( """Hold up, we found "{}" connected to your Pi! Go walk the plank, landlubber! That ain't no Unicorn HAT If this is wrong, chances are you've swapped HATs or pHATs without rebooting. You should use the following in your code for Unicorn HAT: import unicornhat unicornhat.set_layout(unicornhat.HAT) Or for Unicorn pHAT: import unicornhat unicornhat.set_layout(unicornhat.PHAT) """.format(product)) ./examples/phat/0000775000175000017500000000000014223621661014716 5ustar jawn-smithjawn-smith./examples/phat/rainbow.py0000775000175000017500000000206414223621661016736 0ustar jawn-smithjawn-smith#!/usr/bin/env python import colorsys import math import time import unicornhat as unicorn unicorn.set_layout(unicorn.PHAT) unicorn.rotation(0) unicorn.brightness(0.5) print("Reticulating splines") time.sleep(.5) print("Enabled unicorn poop module!") time.sleep(.5) print("Pooping rainbows...") i = 0.0 offset = 30 while True: i = i + 0.3 for y in range(4): for x in range(8): r = 0#x * 32 g = 0#y * 32 xy = x + y / 4 r = (math.cos((x+i)/2.0) + math.cos((y+i)/2.0)) * 64.0 + 128.0 g = (math.sin((x+i)/1.5) + math.sin((y+i)/2.0)) * 64.0 + 128.0 b = (math.sin((x+i)/2.0) + math.cos((y+i)/1.5)) * 64.0 + 128.0 r = max(0, min(255, r + offset)) g = max(0, min(255, g + offset)) b = max(0, min(255, b + offset)) unicorn.set_pixel(x,y,int(r),int(g),int(b)) unicorn.show() time.sleep(0.01) ./examples/phat/README.md0000664000175000017500000000104414223621661016174 0ustar jawn-smithjawn-smithUnicorn pHAT Examples ===================== The examples in this folder must be run with `sudo`, like so: sudo ./rainbow.py or sudo python rainbow.py The examples in this folder are intended for the Unicorn pHAT and are not adapted for the HAT geometry. rainbow.py ---------- This was the first and only pHAT example at release time and was formally known as 'phat_rainbow.py'. It demonstrates the use of `colorsys` to animate through colour hues and is mosty redundant at this point with the now Unified HAT and pHAT 'rainbow.py'. ./examples/random_sparkles.py0000775000175000017500000000112714223621661017524 0ustar jawn-smithjawn-smith#!/usr/bin/env python from random import randint import unicornhat as unicorn print("""Random Sparkles Displays random, colorful sparkles. If you're using a Unicorn HAT and only half the screen lights up, edit this example and change 'unicorn.AUTO' to 'unicorn.HAT' below. """) unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) unicorn.brightness(0.5) width,height=unicorn.get_shape() while True: x = randint(0, (width-1)) y = randint(0, (height-1)) r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) unicorn.set_pixel(x, y, r, g, b) unicorn.show() ./examples/demo.py0000775000175000017500000001037414223621661015270 0ustar jawn-smithjawn-smith#!/usr/bin/env python import colorsys import math import time import unicornhat as unicorn print("""Demo This pixel shading demo transitions between 4 classic graphics demo effects. If you're using a Unicorn HAT and only half the screen lights up, edit this example and change 'unicorn.AUTO' to 'unicorn.HAT' below. """) unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) # tested on pHAT/HAT with rotation 0, 90, 180 & 270 unicorn.brightness(0.5) u_width,u_height=unicorn.get_shape() # twisty swirly goodness def swirl(x, y, step): x -= (u_width/2) y -= (u_height/2) dist = math.sqrt(pow(x, 2)+pow(y,2)) / 2.0 angle = (step / 10.0) + (dist * 1.5) s = math.sin(angle); c = math.cos(angle); xs = x * c - y * s; ys = x * s + y * c; r = abs(xs + ys) r = r * 64.0 r -= 20 return (r, r + (s * 130), r + (c * 130)) # roto-zooming checker board def checker(x, y, step): x -= (u_width/2) y -= (u_height/2) angle = (step / 10.0) s = math.sin(angle); c = math.cos(angle); xs = x * c - y * s; ys = x * s + y * c; xs -= math.sin(step / 200.0) * 40.0 ys -= math.cos(step / 200.0) * 40.0 scale = step % 20 scale /= 20 scale = (math.sin(step / 50.0) / 8.0) + 0.25; xs *= scale ys *= scale xo = abs(xs) - int(abs(xs)) yo = abs(ys) - int(abs(ys)) l = 0 if (math.floor(xs) + math.floor(ys)) % 2 else 1 if xo > .1 and yo > .1 else .5 r, g, b = colorsys.hsv_to_rgb((step % 255) / 255.0, 1, l) return (r * 255, g * 255, b * 255) # weeee waaaah def blues_and_twos(x, y, step): x -= (u_width/2) y -= (u_height/2) xs = (math.sin((x + step) / 10.0) / 2.0) + 1.0 ys = (math.cos((y + step) / 10.0) / 2.0) + 1.0 scale = math.sin(step / 6.0) / 1.5 r = math.sin((x * scale) / 1.0) + math.cos((y * scale) / 1.0) b = math.sin(x * scale / 2.0) + math.cos(y * scale / 2.0) g = r - .8 g = 0 if g < 0 else g b -= r b /= 1.4 return (r * 255, (b + g) * 255, g * 255) # rainbow search spotlights def rainbow_search(x, y, step): xs = math.sin((step) / 100.0) * 20.0 ys = math.cos((step) / 100.0) * 20.0 scale = ((math.sin(step / 60.0) + 1.0) / 5.0) + 0.2 r = math.sin((x + xs) * scale) + math.cos((y + xs) * scale) g = math.sin((x + xs) * scale) + math.cos((y + ys) * scale) b = math.sin((x + ys) * scale) + math.cos((y + ys) * scale) return (r * 255, g * 255, b * 255) # zoom tunnel def tunnel(x, y, step): speed = step / 100.0 x -= (u_width/2) y -= (u_height/2) xo = math.sin(step / 27.0) * 2 yo = math.cos(step / 18.0) * 2 x += xo y += yo if y == 0: if x < 0: angle = -(math.pi / 2) else: angle = (math.pi / 2) else: angle = math.atan(x / y) if y > 0: angle += math.pi angle /= 2 * math.pi # convert angle to 0...1 range shade = math.sqrt(math.pow(x, 2) + math.pow(y, 2)) / 2.1 shade = 1 if shade > 1 else shade angle += speed depth = speed + (math.sqrt(math.pow(x, 2) + math.pow(y, 2)) / 10) col1 = colorsys.hsv_to_rgb((step % 255) / 255.0, 1, .8) col2 = colorsys.hsv_to_rgb((step % 255) / 255.0, 1, .3) col = col1 if int(abs(angle * 6.0)) % 2 == 0 else col2 td = .3 if int(abs(depth * 3.0)) % 2 == 0 else 0 col = (col[0] + td, col[1] + td, col[2] + td) col = (col[0] * shade, col[1] * shade, col[2] * shade) return (col[0] * 255, col[1] * 255, col[2] * 255) effects = [tunnel, rainbow_search, checker, swirl] step = 0 while True: for i in range(500): for y in range(u_height): for x in range(u_width): r, g, b = effects[0](x, y, step) if i > 400: r2, g2, b2 = effects[-1](x, y, step) ratio = (500.00 - i) / 100.0 r = r * ratio + r2 * (1.0 - ratio) g = g * ratio + g2 * (1.0 - ratio) b = b * ratio + b2 * (1.0 - ratio) r = int(max(0, min(255, r))) g = int(max(0, min(255, g))) b = int(max(0, min(255, b))) unicorn.set_pixel(x, y, r, g, b) step += 1 unicorn.show() time.sleep(0.01) effect = effects.pop() effects.insert(0, effect) ./examples/cross.py0000775000175000017500000000360114223621661015470 0ustar jawn-smithjawn-smith#!/usr/bin/env python import time from random import randint import unicornhat as unicorn print("""Cross You should see randomly coloured dots crossing paths with each other. If you're using a Unicorn HAT and only half the screen lights up, edit this example and change 'unicorn.AUTO' to 'unicorn.HAT' below. """) unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) unicorn.brightness(0.5) width,height=unicorn.get_shape() points = [] class LightPoint: def __init__(self): self.direction = randint(1, 4) if self.direction == 1: self.x = randint(0, width - 1) self.y = 0 elif self.direction == 2: self.x = 0 self.y = randint(0, height - 1) elif self.direction == 3: self.x = randint(0, width - 1) self.y = height - 1 else: self.x = width - 1 self.y = randint(0, height - 1) self.colour = [] for i in range(0, 3): self.colour.append(randint(100, 255)) def update_positions(): for point in points: if point.direction == 1: point.y += 1 if point.y > height - 1: points.remove(point) elif point.direction == 2: point.x += 1 if point.x > width - 1: points.remove(point) elif point.direction == 3: point.y -= 1 if point.y < 0: points.remove(point) else: point.x -= 1 if point.x < 0: points.remove(point) def plot_points(): unicorn.clear() for point in points: unicorn.set_pixel(point.x, point.y, point.colour[0], point.colour[1], point.colour[2]) unicorn.show() while True: if len(points) < 10 and randint(0, 5) > 1: points.append(LightPoint()) plot_points() update_positions() time.sleep(0.03) ./examples/rainbow_blinky.py0000775000175000017500000000320414223621661017347 0ustar jawn-smithjawn-smith#!/usr/bin/env python import colorsys import time from sys import exit try: import numpy except ImportError: exit("This script requires the numpy module\nInstall with: sudo pip install numpy") import unicornhat as unicorn print("""Rainbow Blinky Blinks a rainbow from the center of the display. If you're using a Unicorn HAT and only half the screen lights up, edit this example and change 'unicorn.AUTO' to 'unicorn.HAT' below. """) unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) # tested on pHAT/HAT with rotation 0, 90, 180 & 270 unicorn.brightness(0.5) width,height=unicorn.get_shape() if height==width: delta=0 else: delta=2 def make_gaussian(fwhm): x = numpy.arange(0, 8, 1, float) y = x[:, numpy.newaxis] x0, y0 = 3.5, 3.5 fwhm = fwhm gauss = numpy.exp(-4 * numpy.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() for y in range(height): for x in range(width): h = 1.0/(x + y + delta + 1) s = 0.8 if height<=width: v = gauss[x,y+delta] else: v = gauss[x+delta,y] rgb = colorsys.hsv_to_rgb(h, s, v) r = int(rgb[0]*255.0) g = int(rgb[1]*255.0) b = int(rgb[2]*255.0) unicorn.set_pixel(x, y, r, g, b) unicorn.show() end = time.time() t = end - start if t < 0.04: time.sleep(0.04 - t) ./examples/random_blinky.py0000775000175000017500000000174014223621661017171 0ustar jawn-smithjawn-smith#!/usr/bin/env python import colorsys import time from sys import exit try: import numpy except ImportError: exit("This script requires the numpy module\nInstall with: sudo pip install numpy") import unicornhat as unicorn print("""Random Blinky Blinks random yellow-orange-red LEDs. If you're using a Unicorn HAT and only half the screen lights up, edit this example and change 'unicorn.AUTO' to 'unicorn.HAT' below. """) unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) unicorn.brightness(0.5) width,height=unicorn.get_shape() while True: rand_mat = numpy.random.rand(width,height) for y in range(height): for x in range(width): h = 0.1 * rand_mat[x, y] s = 0.8 v = rand_mat[x, y] rgb = colorsys.hsv_to_rgb(h, s, v) r = int(rgb[0]*255.0) g = int(rgb[1]*255.0) b = int(rgb[2]*255.0) unicorn.set_pixel(x, y, r, g, b) unicorn.show() time.sleep(0.01) ./examples/simple.py0000775000175000017500000000102514223621661015626 0ustar jawn-smithjawn-smith#!/usr/bin/env python import time import unicornhat as unicorn print("""Simple Turns each pixel on in turn and updates the display. If you're using a Unicorn HAT and only half the screen lights up, edit this example and change 'unicorn.AUTO' to 'unicorn.HAT' below. """) unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) unicorn.brightness(0.5) width,height=unicorn.get_shape() for y in range(height): for x in range(width): unicorn.set_pixel(x,y,255,0,255) unicorn.show() time.sleep(0.05) time.sleep(1) ./examples/toggle.py0000775000175000017500000000333514223621661015624 0ustar jawn-smithjawn-smith#!/usr/bin/env python from random import randint from time import sleep import unicornhat as unicorn #setup the unicorn hat unicorn.set_layout(unicorn.AUTO) unicorn.brightness(0.5) #get the width and height of the hardware width, height = unicorn.get_shape() def print_header(): #print the program's description print("Unicorn PHat Toggle LEDs with input!") sleep(.5) #give instructions on how to operate print("Press to toggle or + to quit") sleep(.5) def toggle(tog): #toggle has been called determine state if tog: #randomise red, green and blue r = randint(30, 255) g = randint(30, 255) b = randint(30, 255) msg="On!" else: #clear red, green and blue r=0 g=0 b=0 msg="Off!" #print the relevant message print(msg,r,g,b) #set the LEDs to the relevant lighting (all on/off) for y in range(height): for x in range(width): unicorn.set_pixel(x,y,r,g,b) unicorn.show() #return the inverse boolean variable that was passed in return not tog if __name__ == "__main__": #program starts here print_header() #this is the starting state (True=ON) bToggle = True #indefinite loop while True: #call the toggle function with a given state and it will return the inverse bToggle = toggle(bToggle) #pause and await input from keyboard i.e. no characters are checked raw_input("") ./examples/bluesky_greengrass.py0000775000175000017500000000141014223621661020231 0ustar jawn-smithjawn-smith#!/usr/bin/env python import time import unicornhat as unicorn print("""Blue Sky, Green Grass Displays a horizon on your Unicorn HAT/pHAT so you can see which orientation is which. If you're using a Unicorn HAT and only half the screen lights up, edit this example and change 'unicorn.AUTO' to 'unicorn.HAT' below. """) unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) unicorn.brightness(0.5) width,height=unicorn.get_shape() y=0 for x in range(width): unicorn.set_pixel(x,y,0,255,0) unicorn.show() time.sleep(0.05) y=height-1 for x in range(width): unicorn.set_pixel(x,y,0,0,255) unicorn.show() time.sleep(0.05) for y in range(1,3): for x in range(0,y): unicorn.set_pixel(x,y,255,0,0) unicorn.show() time.sleep(0.05) time.sleep(10) ./examples/ascii_pic.py0000775000175000017500000000175514223621661016272 0ustar jawn-smithjawn-smith#!/usr/bin/env python from time import sleep import unicornhat as unicorn print("""ASCII Pic You should see a scrolling image, defined in the below variable ASCIIPIC. If the smiley looks sad, change the rotation from 0 to 180. """) unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) unicorn.brightness(0.5) width,height=unicorn.get_shape() # Every line needs to be exactly 8 characters # but you can have as many lines as you like. ASCIIPIC = [ " X X " ," " ,"X X" ," XXXXXX " ," " ," " ," " ] i = -1 def step(): global i i = 0 if i>=100*len(ASCIIPIC) else i+1 # avoid overflow for h in range(height): for w in range(width): hPos = (i+h) % len(ASCIIPIC) chr = ASCIIPIC[hPos][w] if chr == ' ': unicorn.set_pixel(w, h, 0, 0, 0) else: unicorn.set_pixel(w, h, 255, 0, 0) unicorn.show() while True: step() sleep(0.2) ./examples/test_rotation.py0000775000175000017500000000057314223621661017242 0ustar jawn-smithjawn-smith#!/usr/bin/env python import unicornhat as unicorn import time from random import randint unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) unicorn.brightness(0.4) uh_width,uh_height=unicorn.get_shape() for rot in [0, 90, 180, 270]: print(rot) unicorn.rotation(rot) unicorn.set_pixel(0,0,255,255,255) print(unicorn.get_rotation()) unicorn.show() time.sleep(1) ./examples/drop.py0000775000175000017500000000327214223621661015307 0ustar jawn-smithjawn-smith#!/usr/bin/env python import time from random import randint import unicornhat as unicorn print("""Drop Creates a virtual bucket and fills it with randomly coloured dots. If you're using a Unicorn HAT and only half the screen lights up, edit this example and change 'unicorn.AUTO' to 'unicorn.HAT' below. """) unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) unicorn.brightness(0.5) uh_width,uh_height=unicorn.get_shape() heights = [] def setup(): global heights heights = [] for b in range(0, (uh_width-2)): heights.append(0) unicorn.off() for b in range(0, uh_height): unicorn.set_pixel(0, b, 255, 255, 255) for b in range(0, uh_height): unicorn.set_pixel((uh_width-1), b, 255, 255, 255) for b in range(1, (uh_width-1)): unicorn.set_pixel(b, 0, 255, 255, 255) unicorn.show() def drop_ball(): ball_colour = [randint(100, 255), randint(100, 255), randint(100, 255)] ball_column = randint(0, (uh_width-3)) while heights[ball_column] == (uh_height-1): ball_column = randint(0, (uh_width-3)) height = heights[ball_column] ball_y = (uh_height-1) unicorn.set_pixel(ball_column + 1, ball_y, ball_colour[0], ball_colour[1], ball_colour[2]) unicorn.show() dropcount = (uh_height-2) - height for y in range(0, dropcount): unicorn.set_pixel(ball_column + 1, ball_y, 0, 0, 0) ball_y -= 1 unicorn.set_pixel(ball_column + 1, ball_y, ball_colour[0], ball_colour[1], ball_colour[2]) unicorn.show() time.sleep(0.02) heights[ball_column] += 1 setup() while True: for i in range(0, (uh_width-2)*(uh_height-1)): drop_ball() time.sleep(1) setup() ./examples/clean.py0000775000175000017500000000017614223621661015425 0ustar jawn-smithjawn-smith#!/usr/bin/env python import unicornhat as unicorn def clean(): unicorn.clear() if __name__ == "__main__": clean() ./examples/README.md0000664000175000017500000000565314223621661015252 0ustar jawn-smithjawn-smithUnified Unicorn HAT and pHAT Examples ====================================== The examples in this folder must be run with `sudo`, like so: sudo ./binary_clock.py or sudo python binary_clock.py The library can detect if you're using a Unicorn HAT or a Unicorn pHAT. The recommended initialisation is as follows: ```python import unicornhat as unicorn unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) unicorn.brightness(0.4) width,height=unicorn.get_shape() ``` Explicitly setting the rotation to 0 lets users of your code adapt it to their orientation. Forcing the brightness to 0.4 is for safety. Always use the get_shape() call after having decided on the rotation. If your code uses width and height properly, it should adapt to current and future geometry. Note: If you're only using a Unicorn pHAT you may want to specify it in your code, like so: ```python import unicornhat as unicorn unicorn.set_layout(unicorn.PHAT) ``` Most examples work with both Unicorn HAT and pHAT, using autodetect. Examples that have not been adapted for the pHAT reside in hat folder. Similarly, examples that were specifically designed for the pHAT reside in the phat folder. detect.py --------- Demo code to verify if the auto detection code properly identifies if you have a unicorn HAT or a unicorn pHAT. The code assumes that if height == width then you must have a HAT. IMPORTANT: for the auto detection process to work, Unicorn HAT must be fitted onto the GPIO at boot time. If that was not the case, the auto detection will default to the pHAT layout of 8x4! bluesky_greengrass.py --------------------- Example code to verify the rotation of the screen. The sky (top) should be blue and the grass (bottom) should be green. If you can not re-orientate the screen, use unicorn.rotation(90) or 180 or 270 until you get blue and green in the expected location. demo.py ------- Multi-effect demo; twisty swirly goodness, roto-zooming checker board, weeee waaaah, rainbow search spotlights and zoom tunnel. simple.py --------- Sets each pixel in turn and updates the display. rainbow.py ---------- Demonstrates the use of `colorsys` to animate through colour hues. rainbow_blinky.py ----------------- Blinks a rainbow spot light on and off. Change `fwhm` to make the spot more/less focused (smaller numbers = more focused/larger numbers = less focused). random_blinky.py ---------------- Blinks random yellow-orange-red LEDs. random_sparkles.py ------------------ Random multi-coloured sparkles. drop.py ------- Tetris like filling of a board with random color falling pixels. drop_four_orientation.py ------------------------ Tetris like filling of a board with random color falling pixels. The demo show the 4 rotation in loop. cross.py -------- Crossing random multi-color pixels in the 4 directions. snow.py ------- Falling snowflake pixels. binary_clock.py --------------- Use the first four lines of the display as a binary clock ./examples/hat/0000775000175000017500000000000014223621661014536 5ustar jawn-smithjawn-smith./examples/hat/README.md0000664000175000017500000000217214223621661016017 0ustar jawn-smithjawn-smithUnicorn HAT Examples ==================== The examples in this folder must be run with `sudo`, like so: sudo ./clock.py or sudo python clock.py The examples in this folder are intended for the Unicorn HAT and have not been designed for the pHAT geometry. Feel free to give it a try and move them up inside the main examples folder if you are successful making them work adequately with both boards. candle.py --------- A simple animation simulating a candle flame. candle_with_timer.py -------------------- Builds upon candle.py by adding a fade-out effect to make it useful as a soothing sleep light that will reduce in size and brightnes gradually. clock.py -------- Uses `graphics.py` and shows how you can, but probably shouldn't, display an analogue clock on Unicorn HAT! graphics.py ----------- Used by clock.py eve.py ------ Monitors the usb bus and displays a checkmark when a new device is detected. matrix.py --------- Knock, knock, Neo. show_png.py ----------- Shows how you can open and display a PNG image file (here lofi.png), great for sprite animations. **Requirements:** sudo pip install pillow ./examples/hat/weather-icons/0000775000175000017500000000000014223621661017306 5ustar jawn-smithjawn-smith./examples/hat/weather-icons/README.md0000664000175000017500000001033614223621661020570 0ustar jawn-smithjawn-smith# Animated weather icons for the unicorn-hat Handmade weather animations for unicorn-hat made by pimoroni. each animation is made of 8-16 handmade mini-mini pictures, combined to a sprite. Please use a diffuser for best quality of the animations and for your own safety of course too. `draw_animation(image)` is same as in the 'show-png' example but put into a tiny little function. Put in your image object and you're done. [pimoroni's show-png example](https://github.com/pimoroni/unicorn-hat-hd/blob/master/examples/show-png.py "pimoroni's show-png example") The `draw_animation()` function will loop through all images in the sprite and it will look like a tiny animation. Awesome !! You can change the 'fps' by changing the `cycle_time` variable (0.25 is very smooth) `loop()` loops through all png images in a folder (you might have guessed it) so you can see all possibilities. Usage: ```sudo python weather-icons.py options``` options: - loop - image-file.png example: ```sudo python weather-icons.py loop``` ```sudo python weather-icons.py clear-day.png``` ## unicorn-hat animations 8x8 | | old unicornhat | | |:------------------------------:|:------------------------------------------:|:----------------------------------------------:| | fog | partly-cloudy-day | partly-cloudy-night | | ![fog][fog-sd] | ![partly-cloudy-day][partly-cloudy-day-sd] | ![partly-cloudy-night][partly-cloudy-night-sd] | | clear-night | clear-day | cloudy | | ![clear-night][clear-night-sd] | ![clear-day][clear-day-sd] | ![cloudy][cloudy-sd] | | rain | snow | windy | | ![rain][rain-sd] | ![snow][snow-sd] | ![windy][windy-sd] | | error | raspberry | pimoroni pirate | | ![error][error-sd] | ![raspberry][raspberry-sd] | ![pimoroni_pirate][pimoroni_pirate-sd] | [clear-day-sd]: https://github.com/LoveBootCaptain/unicornhat_weather_icons/blob/master/animation/SD/clear-day.gif "clear-day" [clear-night-sd]: https://github.com/LoveBootCaptain/unicornhat_weather_icons/blob/master/animation/SD/clear-night.gif "clear-night" [cloudy-sd]: https://github.com/LoveBootCaptain/unicornhat_weather_icons/blob/master/animation/SD/cloudy.gif "cloudy" [fog-sd]: https://github.com/LoveBootCaptain/unicornhat_weather_icons/blob/master/animation/SD/fog.gif "cloudy" [partly-cloudy-day-sd]: https://github.com/LoveBootCaptain/unicornhat_weather_icons/blob/master/animation/SD/partly-cloudy-day.gif "partly-cloudy-day" [partly-cloudy-night-sd]: https://github.com/LoveBootCaptain/unicornhat_weather_icons/blob/master/animation/SD/partly-cloudy-night.gif "partly-cloudy-night" [rain-sd]: https://github.com/LoveBootCaptain/unicornhat_weather_icons/blob/master/animation/SD/rain.gif "rain" [snow-sd]: https://github.com/LoveBootCaptain/unicornhat_weather_icons/blob/master/animation/SD/snow.gif "snow" [windy-sd]: https://github.com/LoveBootCaptain/unicornhat_weather_icons/blob/master/animation/SD/windy.gif "windy" [error-sd]: https://github.com/LoveBootCaptain/unicornhat_weather_icons/blob/master/animation/SD/error.gif "error" [raspberry-sd]: https://github.com/LoveBootCaptain/unicornhat_weather_icons/blob/master/animation/SD/raspberry.gif "raspberry" [pimoroni_pirate-sd]: https://github.com/LoveBootCaptain/unicornhat_weather_icons/blob/master/animation/SD/pimoroni.gif "pimoroni pirate" [Buy the old Unicorn HAT on Pimoroni](https://shop.pimoroni.com/products/unicorn-hat "Buy the old Unicorn HAT on Pimoroni") For more animations and icons (also in 16x16 for new unicorn-hat-hd) please visit and support the original project by LoveBootCaptain: [unicornhat_waether_icons by LoveBootCaptain](https://github.com/LoveBootCaptain/unicornhat_weather_icons "Contribute") ./examples/hat/weather-icons/weather-icons.py0000775000175000017500000001123014223621661022430 0ustar jawn-smithjawn-smith#!/usr/bin/env python # The MIT License (MIT) # # Copyright (c) 2016 LoveBootCaptain # # 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. # # ************************************************************* # animated weather icons for the unicorn-hat by LovebootCaptain # ************************************************************* # # The icons in the /icons folder are made of 8-16 individual 8x8 images combined to a sprite. # # draw_animation(image) is same as in the 'show-png' example but put into a tiny little function. # Put in your image object and you're done. The function will loop through all images in the sprite # and it will look like a tiny animation. Awesome !! # # You can change the 'fps' with changing the 'cycle_time' variable (0.25 is very smooth) # # loop() finally loops through all png images in a folder (you might guessed it) so you can see all possibilities. # # usage: # # 'weather-icons.py loop' for all animations or images # # 'weather-icons.py clear-day.png' for a single animation or image import os import time from sys import exit, argv try: from PIL import Image except ImportError: exit('This script requires the pillow module\nInstall with: sudo pip install pillow') import unicornhat as unicorn print(''' ************************************************************* animated weather icons for the unicorn-hat by LovebootCaptain ************************************************************* ''') unicorn.brightness(1) unicorn.rotation(90) folder_path = 'icons/' icon_extension = '.png' width, height = unicorn.get_shape() cycle_time = 0.25 def helper(): print(''' Usage: sudo python weather-icons.py options options: loop image-file.png example: sudo python weather-icons.py loop sudo python weather-icons.py clear-day.png try one of the files from this list: {} '''.format(", ".join(os.listdir(folder_path)))) def draw_animation(image): # this is the original pimoroni function for drawing sprites try: for o_x in range(int(image.size[0] / width)): for o_y in range(int(image.size[1] / height)): valid = False for x in range(width): for y in range(height): pixel = image.getpixel(((o_x * width) + y, (o_y * height) + x)) r, g, b = int(pixel[0]), int(pixel[1]), int(pixel[2]) if r or g or b: valid = True unicorn.set_pixel(x, y, r, g, b) if valid: unicorn.show() time.sleep(cycle_time) except KeyboardInterrupt: unicorn.off() def loop(): print('Looping through all images in folder {}\n' 'CRL+C to skip image'.format(folder_path)) try: for img_file in os.listdir(folder_path): if img_file.endswith(icon_extension): print('Drawing image: {}'.format(folder_path + img_file)) img = Image.open(folder_path + img_file) draw_animation(img) else: print('Not using this file, might be not an image: {}'.format(img_file)) except KeyboardInterrupt: unicorn.off() unicorn.off() def weather_icons(): try: if argv[1] == 'loop': loop() elif argv[1] in os.listdir(folder_path): print('Drawing Image: {}'.format(argv[1])) img = Image.open(folder_path + argv[1]) draw_animation(img) unicorn.off() else: helper() except IndexError: helper() if __name__ == '__main__': weather_icons() ./examples/hat/weather-icons/LICENSE0000664000175000017500000000210014223621661020304 0ustar jawn-smithjawn-smithThe MIT License (MIT) Icons Copyright (c) 2016 LoveBootCaptain 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. ./examples/hat/weather-icons/icons/0000775000175000017500000000000014223621661020421 5ustar jawn-smithjawn-smith./examples/hat/weather-icons/icons/snow.png0000664000175000017500000000034014223621661022112 0ustar jawn-smithjawn-smithPNG  IHDR1~IDATXVI03Ϟ(duD/ܒP#I3DYG3{Wy7{o;+5it$7VÚ7ˣft]ígU{kؾܯ' bZA|m65z 5W*DObsYAP +BIENDB`./examples/hat/weather-icons/icons/partly-cloudy-night.png0000664000175000017500000000222514223621661025047 0ustar jawn-smithjawn-smithPNG  IHDRV!\IDATh]LU v);L*ȇUi-!~$jMjUfc@+jU* I4%N-RJUbLGj]HadR2^gg"Kjyλ睳lfRR:~hgbߟW/&0X7sܜjma?p]: >ti.Ph'KGt0p8 %G<^e./s#8q|VctMgǶ6ed|w2YZSSO-: ݓ_33LNvJ|\Ņ[%B}XtM(,.`c)iLMOwJohB{_6w~^߶}K\v͸l>K/!G".>T~;O4W]II$%%& D}sOF:޷yR =纣{BQQ!Xff^o}}w,!1!"j{p63Il<7]zLsqqsmll`0U?|18g\E:h|"9ԃA}o0xihُ YMwt@t|m z+s ׫tn2rrqy8@[{CqݧR-!s̙̐Nh>?8SF9BxsD#y,3sKif2|exYZ|ً,$4յUVƼ"Մ*ym­:,~kqceh+0 +͌ơ:PMfFbt/ع.|;ѳW2?3c^F2o约Z[?|RlJeA%.2We" $Ңgd%f.uQaaw2J.`84kfX?dURzwg ðqnH {TWtsT=ں݌!ˈAeCx*ˈaeb&Kt n $IENDB`./examples/hat/weather-icons/icons/pimoroni.png0000664000175000017500000000052114223621661022761 0ustar jawn-smithjawn-smithPNG  IHDR1~IDATXֱKBQ}XOI1z4-54XcHM,PexCa{Nswq SD6w˸pdJlW.H>&u$dBm+?쑴Xo=G}tw~, vK1:mݍ=ޮTLT@ʂa]øN aTeH~:lLIENDB`./examples/hat/weather-icons/icons/error.png0000664000175000017500000000027614223621661022265 0ustar jawn-smithjawn-smithPNG  IHDR1~IDATX픱0C2ĩxJC``'F#Ήś_.r݇lHI{``7\hjd sb7_G`\CSnN ,:ͯk4%Aҩ6Y*i]r7=;䁸IENDB`./examples/hat/weather-icons/icons/cloudy.png0000664000175000017500000000045114223621661022426 0ustar jawn-smithjawn-smithPNG  IHDR1~IDATX M t{t` x9hOb[< ޺7-o7dR+zIENDB`./examples/hat/weather-icons/icons/wind.png0000664000175000017500000000034314223621661022070 0ustar jawn-smithjawn-smithPNG  IHDR1~IDATXM fN?+BSgK\} lUkgq"B54y~%Ӟ}gd D36t}{ @j=Lgqt}RJy}+==LN_tkG3YYGwv6`+`%Ϻ5힉Zfk{.V܀> IENDB`./examples/hat/weather-icons/icons/raspberry.png0000664000175000017500000000062414223621661023142 0ustar jawn-smithjawn-smithPNG  IHDR1~[IDATX헽jP?5j@@!oAp t{7С BW73iXI?؊͒3s{\vovJ>~Sk튬˲ۿ/'Mj g QgVZ/]=pca`Aٌ|o-~+w.OڝhIFi*:LAa1e'Np ť)g^LOOz.nG~dXdeuV}{n}]5aNmw}lObZ%|_^]a&wB4y8@E79 ˣ@' i#ݛǏ裏.Vcfϼ455z0 lFˢ^k2R}_'@UU|ߧi|ӷȦu 4ꭞK i1ݦeY mir A1k{bI3>>"L3iMUٿ?KKKȢuCCCo6vD^CUUJ +}# @E*,/D1BH i`ll F%RB&kk fdǎLUU08@0PU!IBD5Y3*@$g: !cc;YNĞДA:+X(K(J&k`lDYQ5EV3P$/P[olxiLAe$jz>19ɮ0 l'&HD8֮gr7ノ?\n۸^@+Izߪ1X,v$_w>Ʊ!IDVۣ&jO6^s$I;!v;a8tAЉb&Ih!jH7[WCpFiwemABxAwBZV/$(hJi6 M.ȲL&c@44|6,5Ӕw 1MTU%n$$y0Țv"')]Sp]A .)I$c蘺Jvd$Ik H.h[=<C=ar.<ϣe$IL~M8x)NAEF6/YY]m@^!W!E>o^U,.tB0OFTBr͂($#p'UA#08tlS[k "(H)Vqh]RYXDZf()Y}zK{>??`l\Wm9[Z u9l'c\eaaػKi,.^eTU!c ydYfyiqgMUQM Q#눒kDIVlݤۗTv_ժ( y ޴|yi\0n֪KZ(!tRXVp'%sswzony`_W_<ַo{Hqemso/w\.^Fp[6+K TF+{C\g^9[ocnn]9x zFo ÈZy~1)nt )CbŘ׋Ab_/^}hpŤmV=IENDB`./examples/hat/weather-icons/icons/clear-day.png0000664000175000017500000000206614223621661022774 0ustar jawn-smithjawn-smithPNG  IHDRV!IDAThюT#g݁,0K 0Dxe3Ā$@W&| $aGӑQf#%x}q6;l̴|眶:Dx@sS(?w[Q5#>m?o^ f<g3o>T%]ƌvcyF~zz}ΞelBkAݮW~t\:pJ.@w[^N*|X8׿Ϛ±Ϯ? xϖU]~lj뷶Ƹݦzq+Kwc:bϩRc5{m7U$ȋ{47J Ӗ7>WK4G~◁)X++vK 7HFτ^E=H@>_UgneAQ˱)rc@/9<cล? tEyHjْ4y)rnpxO?&߳- "¥<&+~: ?On>px7owOAuο/I45m5oR~SSjf/M?jU(*9fF@Sw,ԕyv_}Q~C&D?%\=nπߝS\NGҧ3PRPdT0ѷu YpG#+t{ x +G~g*_څx%`~ X}>V_πIĻEIENDB`./examples/hat/weather-icons/icons/rain.png0000664000175000017500000000034114223621661022056 0ustar jawn-smithjawn-smithPNG  IHDR1~IDATXV[ DgdKEx.H"@q zj~XW{R~gVw Hԑd>+%+[Wv.ƬHwu>3}{ŘA8*ku[p P&9*dȬN> mAZzyl#I &ɘ=IENDB`./examples/hat/weather-icons/icons/fog.png0000664000175000017500000000035014223621661021700 0ustar jawn-smithjawn-smithPNG  IHDR1~IDATXW90 K>ϘxU&$>UJPR0զ)mDDqT2QLJpFomzTpPȦD _LoDpK` h'hFz  ~-;IENDB`./examples/hat/weather-icons/icons/partly-cloudy-day.png0000664000175000017500000000121714223621661024513 0ustar jawn-smithjawn-smithPNG  IHDRV!VIDATh?o0şHRCt(Ń/\2xO !C4.uSIt#p#pÉ:>$m~k[Z+m+Y?@^Anl+O^(̹ܶ'A-A^ـqٴ;sI5hu/@ރry_qqLR;KO p oUer_:޸{??pTLj8s}^oNiS;ΎWOG&>Z>c5{ g~7̝4'u^i淆ySxG uHkMudHG Aֹ&:M T#E)5ğ'>NXGZ㒦kX3d cAC?gM)*7IENDB`./examples/hat/matrix.py0000775000175000017500000000205014223621661016414 0ustar jawn-smithjawn-smith#!/usr/bin/env python import time from random import randint import unicornhat as unicorn print("""Matrix Follow the white rabbit... """) unicorn.set_layout(unicorn.HAT) unicorn.rotation(90) unicorn.brightness(0.5) wrd_rgb = [[154, 173, 154], [0, 255, 0], [0, 200, 0], [0, 162, 0], [0, 145, 0], [0, 96, 0], [0, 74, 0], [0, 0, 0,]] clock = 0 blue_pilled_population = [[randint(0,7), 7]] while True: for person in blue_pilled_population: y = person[1] for rgb in wrd_rgb: if (y <= 7) and (y >= 0): unicorn.set_pixel(person[0], y, rgb[0], rgb[1], rgb[2]) y += 1 person[1] -= 1 unicorn.show() time.sleep(0.1) clock += 1 if clock % 5 == 0: blue_pilled_population.append([randint(0,7), 7]) if clock % 7 == 0: blue_pilled_population.append([randint(0,7), 7]) while len(blue_pilled_population) > 100: blue_pilled_population.pop(0) ./examples/hat/eve.py0000775000175000017500000000527114223621661015677 0ustar jawn-smithjawn-smith#!/usr/bin/env python import colorsys import math import random import time from sys import exit try: import glib except ImportError: exit("This script requires the glib module") try: import gudev except ImportError: exit("This script requires the gudev module") import unicornhat as unicorn unicorn.set_layout(unicorn.HAT) unicorn.rotation(0) unicorn.brightness(0.5) sin_off = [[0]*8 for i in range(8)] for y in range(8): for x in range(8): sin_off[x][y] = random.random() * (math.pi * 2) tick_mask = [[0,0,0,0,0,0,0,0], [0,0,0,0,0,0,1,0], [0,0,0,0,0,1,1,1], [0,0,1,0,1,1,1,0], [0,1,1,1,1,1,0,0], [0,0,1,1,1,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,0,0,0,0]] steps_per = 16 def background(x, y, step): v = math.sin(sin_off[x][y] + (step / 10.0)) g = v + 1.0 g = g * 20.0 g += 20 v = math.sin(sin_off[y][x] + (step / 20.0)) b = v + 1.0 b = b * 15.0 b += 20 r = 0 g /= (r/50) + 1 b /= (r/50) + 1 pos = int(step / steps_per) fill = int((float(step % steps_per) / float(steps_per)) * 8.0) if x < pos: r = math.sin(sin_off[y][x] + (step / 20.0)) r *= 30 r += 80 g = 0 b = 0 elif x == pos and y < fill: r = math.sin(sin_off[y][x] + (step / 20.0)) r *= 30 r += 80 g = 0 b = 0 return (g, r, b) def effect(): # trigger effect for i in range(steps_per * 8): for y in range(8): for x in range(8): r, g, b = background(x, y, i) r = int(max(0, min(255, r))) g = int(max(0, min(255, g))) b = int(max(0, min(255, b))) unicorn.set_pixel(x, y, r, g, b) unicorn.show() time.sleep(0.01) for i in range(200): v = (math.sin(i / 6.0) + 1.0) / 2.0 for y in range(8): for x in range(8): r = 0 b = 0 g = 100 g *= tick_mask[y][x] g *= v r = int(max(0, min(255, r))) g = int(max(0, min(255, g))) b = int(max(0, min(255, b))) unicorn.set_pixel(x, y, r, g, b) unicorn.show() time.sleep(0.02) def clear(): for y in range(8): for x in range(8): unicorn.set_pixel(x, y, 0, 0, 0) unicorn.show() def callback(client, action, device, user_data): if action == "add": effect() if action == "remove": clear() client = gudev.Client(["usb/usb_device"]) client.connect("uevent", callback, None) loop = glib.MainLoop() loop.run() ./examples/hat/candle_with_timer.py0000775000175000017500000001330114223621661020572 0ustar jawn-smithjawn-smith#!/usr/bin/env python import colorsys import math import time import datetime from random import randint import unicornhat as unicorn print("""Unicorn HAT: Candle This example simulates a flickering candle flame. Press Ctrl+C to exit! """) unicorn.rotation(180) # 180 works when powercord at top of RPi bright = 0.5 # this variable allows dimming the candle as timer nears the end unicorn.brightness(bright) # brightness of 0.2 is too low b/c the top dim part of the flame doesn't show up # 0.26 to 0.31 shape of flame OK, nice low warm color, but no constrast b/t light and dark parts # 0.32 to 0.4 works very well, looks normal # 1.0 is very bright, and you can't look at the flame unless you have a diffuser over it width, height = unicorn.get_shape() # buffer to contain candle "heat" data candle = [0] * 256 # create a palette for mapping heat values onto colours palette = [0] * 256 for i in range(0, 256): h = i / 5.0 h /= 360.0 s = (1.0 / (math.sqrt(i / 50.0) + 0.01)) s = min(1.0, s) s = max(0.0, s) v = i / 200.0 if i < 60: v = v / 2 v = min(1.0, v) v = max(0.0, v) r, g, b = colorsys.hsv_to_rgb(h, s, v) palette[i] = (int(r * 255.0), int(g * 255.0), int(b * 255.0)) def set_pixel(b, x, y, v): b[y * 16 + x] = int(v) # edited 16 to 8 def get_pixel(b, x, y): # out of range sample lookup if x < 0 or y < 0 or x >= 16 or y >= 16: # edited 16 to 8 return 0 # subpixel sample lookup if isinstance(x, float) and x < 7: # edited 15 to 7 f = x - int(x) return (b[int(y) * 16 + int(x)] * (1.0 - f)) + (b[int(y) * 16 + int(x) + 1] * (f)) # edited 16 to 8 # fixed pixel sample lookup return b[int(y) * 16 + int(x)] # edited 16 to 8 step = 0 # set up the timer minutes = 15 # how long the candle burns for start_time = time.time() end_time = start_time + (60 * minutes) # spanning midnight OK, since end_time can be greater than 24 hrs # Max time period for candle to taper down at end of timer. Multiply by starting brightness to get effective taper time. # Example: brightness=0.5 * fade_minutes=10 --> 5 minute fade-out period fade_minutes = 30 print('Lighting a candle for {} minutes.'.format(round( ( end_time - start_time )/60, 0 ))) try: while time.time() < end_time: # If near the end of the timer, taper down the candle by lowering brighness. # The candle also appears progressively smaller, # because the edge of the flame gets progressively too dim to illuminate the LEDs. # By default, at brightness below 0.3 unicornhat prints a warning. # Brightness down to 0.2 works for the flame, allowing a more complete fade than min of 0.3. # If desired, edit "unicornhat.py" to only print a warning at brightness < 0.2 (brightness < 20 in the code), # so the script doesn't trigger a cascade of warning messages near the end. # Rounding the time reduces number of times if loop executes if round((end_time - time.time())/(60*fade_minutes),2) < bright: bright = max(0.2,round((end_time - time.time())/(60*fade_minutes),2)) # assign gradually lower brightness level unicorn.brightness(bright) # pass brightness to unicornhat time.sleep(0.001) # slows the flame as it dims #print('brightness is',bright) # uncomment to monitor brightness values # step for waving animation, adds some randomness step += randint(0, 15) # clone the current candle temp = candle[:] # seed new heat v = 500 set_pixel(candle, 1, 7, v) # Converting from unicornhatHD, subtracted 8 from these set_pixel(candle, 2, 7, v) # since unicornhat is half the size. set_pixel(candle, 3, 7, v) # candle is a list, and 2 numbers are used to set_pixel(candle, 4, 7, v) # calculate a position in list set_pixel(candle, 1, 6, v) # that will be assigned integer value v set_pixel(candle, 2, 6, v) set_pixel(candle, 3, 6, v) set_pixel(candle, 4, 6, v) # blur, wave, and shift up one step # v is changed then a pixel is set, 8x8 times, then all assigned to candle for x in range(0, 8): for y in range(0, 8): # 8x8 is 64, length of list candle, and size of unicornhat s = math.sin((y / 30.0) + (step / 10.0)) * ((16 - y) / 20.0) v = 0 for i in range(0, 3): # range seems to scale height of low bright part of flame for j in range(0, 3): # range seems to scale height of top dim part of flame r = randint(0, 2) - 1 # provides some slight color variations v += get_pixel(candle, x + i + s - 1, y + j) v /= 12 # denominator scales the size of flame, so larger number-->smaller flame # 11 is too tall, the top of the flame is clipped off # 12 fills the unicornhat perfectly # 16 is about 5 pixels high, and five pixels wide, barely ok # 20 is too small at about 3 pixels high, seems like all one color set_pixel(temp, x, y, v) time.sleep(.0026) # adjusts how fast the flame dances around candle = temp # copy candle into unicornhat with palette # from unicornhatHD, adjusted to 8x8 values of candle, convert from hsv to rbg # and painted onto unicornhat for x in range(0, 8): for y in range(0, 8): o = (i * 3) + 1 r, g, b = palette[max(0, min(255, get_pixel(candle, x, y)))] unicorn.set_pixel(x, y, r, g, b) unicorn.show() except KeyboardInterrupt: unicorn.off() ./examples/hat/lofi.png0000664000175000017500000002473014223621661016203 0ustar jawn-smithjawn-smithPNG  IHDRcP,tEXtCreation TimeSun 29 Nov 2009 17:56:02 -0000KۼtIME 5eW) pHYsiTSgAMA a)/IDATx] -Uu{kE+ Rjl"DRn+&`TLx\5RRV[j+LE)!5B"hEJĤDj%QiD=o:k=5d>3cZ{ۦIGvZ~͇L/?4پ6O3;c7{x? .`F~]ok/xWYpW߳P)\Tr8 [ J((K+o]KO4^״u?ZVBSݸ k3've 1GqNˍ6|]r8n7~ϛʧk &2oh{N,$Gyȍj8Gҷ(||?S7=և<$9`865T>m塏?όg5'4W>&=|wO:/;󰉺|g %G\6W9"x-}5|ʮFirPKn94븎ˆz_|SW&7֢m}b8"iAa?nG/7J;7?b?r/zuG] u |زEBG[WIk6x'y~6\4_ qMYuƺ5fٍ̺ڜ}!v#k8Q7XJIWG/1w=d4n[}x_n]i:R? :_{z{3^}h @%pK|03{p#]Qf^|})}_ h{IG^$*RZ/NgCxs=}$NֻJzh%Yp?ҽ3#fApX?zS|_A~me&!G>"~ 7t]q;PZVNu9.IH|ە:.lpoYc?j-("b̍ŽBd Œ-K:}P,y P"yJ|5VD{I26}%Kloy_k:qIˋpATg`p q[,҇IePxB/L Yl R(OϢ%Yl>QbKsDD>i=i ctNqp9<ₛ/HXN;XnV SxhDUΌM0gD=~ZL{F ֫O)rBdžC(/u楸-څ2/B~*<\? ס>ZʱJJx9H59[<Dv1AǞ8|`X8꧃{Mf υq{#($tIX|]:c??}8d9fWZ5!lۿ&w3o-K(_AmO\t|ן=p-]ջ%.EK%9* ;S ,o#> vcBg'>25V gw?|~=O|so[8 } ~z{0:礣rYQ=Ҟlh1|tFx~,^Ī'zDD._rF7*FHYv'*ueˈZz05}zzM!җ@fvD#^A}R7V4 ׳7^w{nޣw,{8qp}<P%z.fPGdOpd=eh.(YPMk=\ZpI#k>-x%>n=9?kg#4$?5{?|${* t43n7H2_{  '8n<'$zvku{+k|6!CRR;-HiJҌpj*E*H%uVX{Qꁣ؃Mf/$=yPy9 Kgx^ VYxpzM$[4|y7 p}zB=!1-y?.QSнͳy+xO:eW+ V(>Ͳˇ:$$E8[¤BE!o_hpsc^4fO*\T\>|lpQf #2n06vբTz#0 XlQWqddB/B.NkX"IXFF3(#D߲vUO(gICpԓ~3K-jVUU? k:0У$'i {f\9/g}US邵T(j : 86c j| ;oMPZ֪~I 7d|ڤ5dAF#d;s5\+ CBق?]zgeW;x(X$ׂ_m``%;~򟿜qE "L/~_ >V'h,g4[V)p&.r s( gqk8?u((szxU);ޢ!t 45460/6rV踽(cXx>ysJcKr~<<= +>ĸ$={-T_v)_߇q5 FBĿ]UZ _BIV"Uֈg|8&wW}]FğSGyߎ_{eC=ÓZi k~@үđ& ޾s8nj\GY)v3<韔kwWQ_;6{1lÇ>{n VLY>o%a* _wc4}59G 5 <͊ |dd,ZqZ0 I҇oV>9C16H5<װ|>'G{ʙtU0-Ȭ&*?x0"&bcժ-gR|U8K窞)QQT 9c~kGv"CkWG3=2~Yn~oL9QPL̓R oqk3M΅UX4!>63HB}(iry%$^;6B>gkj-M#Mj^ e׿hr7[ POzI9dzybQ8/jDϽʳϗ[!_qְk,ʿ Sȇmdqoj#Hqᩍ ģAL}G'Pvc?֡Vb^} kװ|"2k D)ZQϬDFQF*GC%l卽4F+5^%e׳kx^5O7DustP\'X\%yXr?I].wٳ#huh 슫^;p^Ҵ+ =C==38[y";xpRd'4ow>?YECPi!$v%Ϸul\vYU]+Ԍo_ؔWK;7z]~d[9֊Z7 VvJ[CsӇ^i*}W;pHnj~#oN!f'8hW">SZQOWE`}g> #-nɾpt aľMC{r bgy? $Y[:056#\:i֖w{5yv(J/ Q f3W[ܦMq g9//5+Qkh K}V7jЊ,FAzϿwo̮%[FvK@74 \KXPldyh[e,N9wcHN0?ۻ$ ?{d-^bS\m{x!;8X?=W5Y%vu 2O 2 @,@.=`ȵ~h9 q~af;j?("_‘.p{/ .].T:+au==~AG Q?jâj⹉Ay c¯o^fP)1'3Ox ϸ~ʲe38]sbz%Ǟ^&=q;pXy~y~+x\ 38ANtMc>򙦹f'+_[_߳Ydx[lola^)O(\Py:@kx+qNEq] " mnzΌ^?-b=ŞU! \ NJiz_ebQ|Ֆ?3öĔ=ZM< NdBtvo7uR>NX%Kq~+ +79T2Y礣ZPBC+!D$K!^+"M?0U;c'Nq,ː%p$xȐ8 @>*<ê g5nMT⌌F?b"JZ<73zOò8Gۋs/~P]Ant_W| v<%Hԥc2Bg8#܌w>Ljq2wƻB4sw70IۇɊVlnkIhxn`oWw5 ۸< ǣJxdžG# D`&iԖ=%vN޼s8x ˥+VOALc )rÓ#`gOIM=?˓ei[< M@'/QYV W!k/}e~`l8=>Q.*ޘ\eﭖk'2'Ɋʟx:= L񬤒܉ .(i0ƢjU{h:Pvq2:iw97h KL o 7ES|?>٠$1S$7<}~TRBWy=%'_I0'fKRy.q1\N9d w>mᵞ|d ӰW_)ơ>ŷO/$iBmV$vR蹄}Ck7(|[}˪D98Z o]3Ep/Oʕ;v372̩T5Jm7y5jw];i`r^).YfFK8q׏`nwA*qXjtĐ열^ `6 3[̸{d2֋Wgˮ -~_i>*N˗8۾BѲc@eo,,?Gpqrq}ݍ;f3  Ŝh=Ć=qrGsy/ȒrVߎgP@yC&Vͣ׵}^];GB:jsk {^7=$WnC|fԝ0|psB?܍1%Y{/\#?5 ɻj׼0Õs0d{sHZSv*.7=;Z5VJ avpŇޛjc#f$\:>/Yns4ҿ:wrƋi- Z*eIP YAڻ/ѤF]S.oMY#vR9;zm'>կF&Zj\8L>+& gh}r<T*E߾-"qs" GE@d1yyuT~ӞVOP<[vkjzp%T(8Wݾ5n_GUZ:|fN $gXJ4wg#(ҧL;pE輼,k +^oؿ^½oï^Ooݭ+ jKZ= m=O>'Sqo /pQʳtϦ&W/oXֹWVr1x&{eQ65G7]tӀOTu툏$6]f{3TkIO3x#Vk>%oT9.,fDUYNv?acZL"~DIwsGu[%#6zPv0DT5u0oiK[/+V!FxhFd|>GF4{zWT~ʻft :w\}yC BwPٸEqG?{ Glр?#N:+jK'vmk|S@^cz{> &u,e手62jԈgk/\t6TAǦy"~XPNeS)nM[ 7Yݶ ~_9z^ J. cq9Wz_:i|.&RqfK7t՛qH&n;l t-QfcvOWiQ6[ uƂaI9t):d_rˡ[HK:c(C<:ri )MB9 `⮒Ċ(=6 Gp'R+qiv'~]B>q]aV=J%l̚ O;QCD*+ _&V$ڗA4=TZ=p#0d7r &F=mqz^*?=%mh(`>o ^@w2z 3y=0;%":`IJ6hgGlv `GA*70& 0*ֈ9wdG(` m'2,y͸#J7Ytmk|6)״ ,yؓu.;*VRc;3Y g@ãHј0̔#zKIMmф.gd[켫(8^ v19:kT$rѻ=}J\ud)K_5y`XrK;j5:O{W$W`J|ݺߋT>Qc'Y axh>5>4Tp୷Gt GYda., Xz |hAB/Sml)H[[L3V\#T~F* QIU(aRТ aDc>mvsɥV$S6xQ>+ 8zV͜gDBgIS34IHђYl G3 hvpDMC~CǸTo;=kwȺ *e i;5?zBiIENDB`./examples/hat/clock.py0000775000175000017500000000332414223621661016210 0ustar jawn-smithjawn-smith#!/usr/bin/env python import signal import threading import time from graphics import Drawing, Color import unicornhat as unicorn unicorn.set_layout(unicorn.HAT) unicorn.rotation(0) unicorn.brightness(0.5) print("""Clock Displays an analog clock. Automatically dims at night. """) class UnicornDrawing(Drawing): def __init__(self): Drawing.__init__(self,8,8) ''' All drawing operations use the pixel method so we override it for UnicornHat ''' def pixel(self, x, y, col): if x < 0 or x > 7 or y < 0 or y > 7: return False self.buffer[(x,y)] = col unicorn.set_pixel(x, y, col.r, col.g, col.b) def show(self): unicorn.show() d = UnicornDrawing() # X offset of clock centre O_X = 3 # Y offset of clock centre O_Y = 3 # Radius of clock R = 3 # Rotation offset of clock, set to 0, 90, 180, 270, etc unicorn.rotation(0) def setBrightness(currenttime): currenthour = currenttime.tm_hour # if it's between 10 am and 8 pm, # use dimmer brightness if(currenthour < 10 or currenthour > 20): unicorn.brightness(0.5) else: unicorn.brightness(0.8) def tick(): currenttime = time.localtime() currenthour = currenttime.tm_hour currentmin = currenttime.tm_min currentsec = currenttime.tm_sec # Set daytime or nighttime brightness setBrightness(currenttime) d.clear() # Draw the circle around the clock d.circle(O_X,O_Y,R,Color(255,0,255)) # Draw the clock hands d.circle_line(O_X,O_Y,R-1,(-360.0*((currenthour % 12)/12.0)),Color(255,0,0)) d.circle_line(O_X,O_Y,R-1,(-360.0*(currentmin/60.0)), Color(0,255,0)) d.circle_line(O_X,O_Y,R-1,(-360.0*(currentsec/60.0)), Color(0,0,255)) # draw buffer to hardware d.show() threading.Timer(1,tick).start() tick() ./examples/hat/candle.py0000775000175000017500000000770714223621661016354 0ustar jawn-smithjawn-smith#!/usr/bin/env python import colorsys import math import time from random import randint import unicornhat as unicorn print("""Unicorn HAT: Candle This example simulates a flickering candle flame. Press Ctrl+C to exit! """) unicorn.rotation(180) # 180 is correct when powercord is at top of RPi unicorn.brightness(0.5) # brightness of 0.2 is too low b/c the top dim part of the flame doesn't show up # 0.26 to 0.31 shape of flame OK, nice low warm color, but no constrast b/t light and dark parts # 0.32 to 0.5 works very well, looks normal width, height = unicorn.get_shape() # buffer to contain candle "heat" data candle = [0] * 256 # create a palette for mapping heat values onto colours palette = [0] * 256 for i in range(0, 256): h = i / 5.0 h /= 360.0 s = (1.0 / (math.sqrt(i / 50.0) + 0.01)) s = min(1.0, s) s = max(0.0, s) v = i / 200.0 if i < 60: v = v / 2 v = min(1.0, v) v = max(0.0, v) r, g, b = colorsys.hsv_to_rgb(h, s, v) palette[i] = (int(r * 255.0), int(g * 255.0), int(b * 255.0)) def set_pixel(b, x, y, v): b[y * 16 + x] = int(v) # edited 16 to 8 def get_pixel(b, x, y): # out of range sample lookup if x < 0 or y < 0 or x >= 16 or y >= 16: # edited 16 to 8 return 0 # subpixel sample lookup if isinstance(x, float) and x < 7: # edited 15 to 7 f = x - int(x) return (b[int(y) * 16 + int(x)] * (1.0 - f)) + (b[int(y) * 16 + int(x) + 1] * (f)) # edited 16 to 8 # fixed pixel sample lookup return b[int(y) * 16 + int(x)] # edited 16 to 8 step = 0 try: while True: # step for waving animation, adds some randomness step += randint(0, 15) # clone the current candle temp = candle[:] # seed new heat v = 500 set_pixel(candle, 1, 7, v) # Converting from unicornhatHD, subtracted 8 from these set_pixel(candle, 2, 7, v) # since unicornhat is half the size. set_pixel(candle, 3, 7, v) # candle is a list, and 2 numbers are used to set_pixel(candle, 4, 7, v) # calculate a position in list set_pixel(candle, 1, 6, v) # that will be assigned integer value v set_pixel(candle, 2, 6, v) set_pixel(candle, 3, 6, v) set_pixel(candle, 4, 6, v) # blur, wave, and shift up one step # v is changed then a pixel is set, 8x8 times, then all assigned to candle for x in range(0, 8): for y in range(0, 8): # 8x8 is 64, length of list candle, and size of unicornhat s = math.sin((y / 30.0) + (step / 10.0)) * ((16 - y) / 20.0) v = 0 for i in range(0, 3): # range seems to scale height of low bright part of flame for j in range(0, 3): # range seems to scale height of top dim part of flame r = randint(0, 2) - 1 # provides some slight color variations v += get_pixel(candle, x + i + s - 1, y + j) v /= 12 # denominator scales the size of flame, so larger number-->smaller flame # 11 is too tall, the top of the flame is clipped off # 12 fills the unicornhat perfectly # 16 is about 5 pixels high, and five pixels wide, barely ok # 20 is too small at about 3 pixels high, seems like all one color set_pixel(temp, x, y, v) time.sleep(.003) # adjusts how fast the flame dances around candle = temp # copy candle into unicornhat with palette # from unicornhatHD, adjusted to 8x8 values of candle, convert from hsv to rbg # and painted onto unicornhat for x in range(0, 8): for y in range(0, 8): o = (i * 3) + 1 r, g, b = palette[max(0, min(255, get_pixel(candle, x, y)))] unicorn.set_pixel(x, y, r, g, b) unicorn.show() except KeyboardInterrupt: unicorn.off() ./examples/hat/show_png.py0000775000175000017500000000205014223621661016734 0ustar jawn-smithjawn-smith#!/usr/bin/env python ''' This basic example shows use of the Python Pillow library: sudo pip-3.2 install pillow # or sudo pip install pillow The tiny 8x8 chars in lofi.png are from Oddball: http://forums.tigsource.com/index.php?topic=8834.0 Licensed under Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. ''' import signal import time from sys import exit try: from PIL import Image except ImportError: exit("This script requires the pillow module\nInstall with: sudo pip install pillow") import unicornhat as unicorn unicorn.set_layout(unicorn.HAT) unicorn.rotation(90) unicorn.brightness(0.5) img = Image.open('lofi.png') for o_x in range(int(img.size[0]/8)): for o_y in range(int(img.size[1]/8)): for x in range(8): for y in range(8): pixel = img.getpixel(((o_x*8)+y,(o_y*8)+x)) print(pixel) r, g, b = int(pixel[0]),int(pixel[1]),int(pixel[2]) unicorn.set_pixel(x, y, r, g, b) unicorn.show() time.sleep(0.5) ./examples/hat/graphics.py0000664000175000017500000000647514223621661016724 0ustar jawn-smithjawn-smith''' This file is used in UnicornHat examples for drawing things. ''' import colorsys import math class Color(): def __init__(self, r, g, b): self.r = r self.g = g self.b = b def __str__(self): r = hex(self.r)[2:] g = hex(self.g)[2:] b = hex(self.b)[2:] return ''.join([r,g,b]) def rgb(self): return (self.r, self.g, self.b) def hsv(self): return colorsys.rgb_to_hsv(self.r, self.g, self.b) class Drawing(): def __init__(self,width=8,height=8): self.width = width self.height = height self.buffer = {} for x in range(width): for y in range(height): self.buffer[(x,y)] = Color(0,0,0) def fill(self, col = Color(0,0,0)): for x in range(self.width): for y in range(self.height): self.pixel(x, y, col) def clear(self): self.fill(Color(0,0,0)) ''' Creates a color tuple from r, g, b elements with values 0 to 255 ''' def color_from_rgb(self, r, g, b): return (r, g, b) ''' Creates a color tuple from h, s, v elements with values 0.0 to 1.0 ''' def color_from_hsv(self, h, s, v): rgb = colorsys.hsv_to_rgb(h, s, v) return color_from_rgb( int(rgb[0]*255), int(rgb[1]*255), int(rgb[2]*255) ) def pixel(self, x, y, col): self.buffer[(x,y)] = col def circle(self, x0, y0, r, col=Color(0,0,0), fill=None): f = 1 - r ddf_x = 1 ddf_y = -2 * r x = 0 y = r self.pixel(x0, y0 + r, col) self.pixel(x0, y0 - r, col) self.pixel(x0 + r, y0, col) self.pixel(x0 - r, y0, col) while x < y: if f >= 0: y -= 1 ddf_y += 2 f += ddf_y x += 1 ddf_x += 2 f += ddf_x self.pixel(x0 + x, y0 + y, col) self.pixel(x0 - x, y0 + y, col) self.pixel(x0 + x, y0 - y, col) self.pixel(x0 - x, y0 - y, col) self.pixel(x0 + y, y0 + x, col) self.pixel(x0 - y, y0 + x, col) self.pixel(x0 + y, y0 - x, col) self.pixel(x0 - y, y0 - x, col) def circle_line(self, origin_x, origin_y, radius, angle, col): angle = (angle / 360.0) * (2*math.pi) x = origin_x + radius * math.sin(angle) y = origin_y + radius * math.cos(angle) self.line( origin_x, origin_y, int(round(x)), int(round(y)), col ) def line(self, x0, y0, x1, y1, col=Color(0,0,0)): s = abs(y1 - y0) > abs(x1 - x0) if s: x0, y0 = y0, x0 x1, y1 = y1, x1 if x0 > x1: x0, x1 = x1, x0 y0, y1 = y1, y0 dx = x1 - x0 dy = abs(y1 - y0) err = dx / 2 ystep = 0 if y0 < y1: ystep = 1 else: ystep = -1 while x0<=x1: if s: self.pixel(y0, x0, col) else: self.pixel(x0, y0, col) err -= dy if err < 0: y0 += ystep err += dx x0+=1 def test(self): out = '' for y in range(self.height): for x in range(self.width): if self.buffer[(x,y)].rgb() == (0,0,0): out += ' ' else: out += '##' out += '\n' print(out) if __name__ == '__main__': print("Testing color") print(Color(255,50,20)) g = Drawing() g.test() print("Testing circle") g.circle(4,4,3,Color(255,255,255)) g.test() g.clear() print("Testing line") g.line(0,0,7,7,Color(255,255,255)) g.test() g.clear() print("Testing circle line") g.circle_line(4,4,3,0,Color(255,255,255)) g.test() ./examples/drop_four_orientation.py0000775000175000017500000000346514223621661020761 0ustar jawn-smithjawn-smith#!/usr/bin/env python import time from random import randint import unicornhat as unicorn print("""Drop: Four Orientation The same as Drop, but showing the virtual bucket in 4 different orientations. If you're using a Unicorn HAT and only half the screen lights up, edit this example and change 'unicorn.AUTO' to 'unicorn.HAT' below. """) unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) unicorn.brightness(0.5) uh_width,uh_height=unicorn.get_shape() heights = [] def setup(): global heights heights = [] for b in range(0, (uh_width-2)): heights.append(0) unicorn.off() for b in range(0, uh_height): unicorn.set_pixel(0, b, 255, 255, 255) for b in range(0, uh_height): unicorn.set_pixel((uh_width-1), b, 255, 255, 255) for b in range(1, (uh_width-1)): unicorn.set_pixel(b, 0, 255, 255, 255) unicorn.show() def drop_ball(): ball_colour = [randint(100, 255), randint(100, 255), randint(100, 255)] ball_column = randint(0, (uh_width-3)) while heights[ball_column] == (uh_height-1): ball_column = randint(0, (uh_width-3)) height = heights[ball_column] ball_y = (uh_height-1) unicorn.set_pixel(ball_column + 1, ball_y, ball_colour[0], ball_colour[1], ball_colour[2]) unicorn.show() dropcount = (uh_height-2) - height for y in range(0, dropcount): unicorn.set_pixel(ball_column + 1, ball_y, 0, 0, 0) ball_y -= 1 unicorn.set_pixel(ball_column + 1, ball_y, ball_colour[0], ball_colour[1], ball_colour[2]) unicorn.show() time.sleep(0.02) heights[ball_column] += 1 while True: for rot in [0, 90, 180, 270]: unicorn.rotation(rot) uh_width,uh_height=unicorn.get_shape() setup() for i in range(0, (uh_width-2)*(uh_height-1)): drop_ball() time.sleep(1) ./examples/snow.py0000775000175000017500000000332714223621661015332 0ustar jawn-smithjawn-smith#!/usr/bin/env python from random import randint from time import sleep import unicornhat as unicorn print("""Snow Draws random white pixels to look like a snowstorm. If you're using a Unicorn HAT and only half the screen lights up, edit this example and change 'unicorn.AUTO' to 'unicorn.HAT' below. """) unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) unicorn.brightness(0.5) width,height=unicorn.get_shape() rows = [] row_pointer = 0 def init(): # create a buffer of blank rows for i in range(height): rows.append(get_blank_row()) def get_blank_row(): # generate a blank row return [0] * width def get_new_row(): # get a new blank row and add a random brightness snowflake to a random column row = get_blank_row() row[randint(0, width - 1)] = 50 + randint(0, 155) return row def update_display(): # keep track of the row we are updating c = row_pointer for h in range(height): for w in range(width): # val is between 50 and 255 val = rows[c][w] # invert coordinates unicorn.set_pixel((width - 1) - w, (height - 1) - h, val, val, val) c += 1 if c > height - 1: c = 0 unicorn.show() def step(): global row_pointer # add new row at current row pointer # leave other rows the same, display will start from this one which overwrites the # oldest existing row from the last time we updated the display rows[row_pointer] = get_new_row() update_display() # determine next row pointer, wrapping around if we went past zero row_pointer -= 1 if row_pointer < 0: row_pointer = height - 1 init() while True: step() sleep(0.3) ./examples/figlet.py0000775000175000017500000000253114223621661015612 0ustar jawn-smithjawn-smith#!/usr/bin/env python from time import sleep from sys import exit try: from pyfiglet import figlet_format except ImportError: exit("This script requires the pyfiglet module\nInstall with: sudo pip install pyfiglet") import unicornhat as unicorn print("""Figlet You should see scrolling text that is defined in the TXT variable. If the text moves in the wrong direction, change the rotation from 0 to 180. Text output is kind of limited on a pHAT of course because most letters don't fit on the small display of 4x8. """) unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) unicorn.brightness(0.5) width,height=unicorn.get_shape() TXT = "HELLO" figletText = figlet_format(TXT+' ', "banner", width=1000) # banner font generates text with heigth 7 textMatrix = figletText.split("\n")[:width] # width should be 8 on both HAT and pHAT! textWidth = len(textMatrix[0]) # the total length of the result from figlet i = -1 def step(): global i i = 0 if i>=100*textWidth else i+1 # avoid overflow for h in range(height): for w in range(width): hPos = (i+h) % textWidth chr = textMatrix[w][hPos] if chr == ' ': unicorn.set_pixel(width-w-1, h, 0, 0, 0) else: unicorn.set_pixel(width-w-1, h, 255, 0, 0) unicorn.show() while True: step() sleep(0.2) ./examples/game_of_life.py0000775000175000017500000000463114223621661016737 0ustar jawn-smithjawn-smith#!/usr/bin/env python import random import time import unicornhat as unicorn print("""Game Of Life Runs Conway's Game Of Life on your Unicorn HAT, this starts with a random spread of life, so results may vary! If you're using a Unicorn HAT and only half the screen lights up, edit this example and change 'unicorn.AUTO' to 'unicorn.HAT' below. """) try: xrange except NameError: xrange = range unicorn.set_layout(unicorn.AUTO) unicorn.rotation(90) unicorn.brightness(0.5) width,height=unicorn.get_shape() size = width*height class GameOfLife: def __init__(self): self.board = [int(7 * random.getrandbits(1)) for _ in xrange(size)] self.color = [[154, 154, 174], [0, 0, 255], [0, 0, 200], [0, 0, 160], [0, 0, 140], [0, 0, 90], [0, 0, 60], [0, 0, 0,]] def value(self, x, y): index = ((x % width) * height) + (y % height) return self.board[index] def neighbors(self, x, y): sum = 0 for i in xrange(3): for j in xrange(3): if i == 1 and j == 1: continue if self.value(x + i -1, y + j -1) == 0: sum = sum + 1 return sum def next_generation(self): new_board = [False] * size for i in xrange(width): for j in xrange(height): neigh = self.neighbors(i, j) lvl = self.value(i, j) if lvl == 0: if neigh < 2: new_board[i * height + j] = min(7, lvl + 1) elif 2 <= neigh <= 3: new_board[i * height + j] = 0 else: new_board[i * height + j] = min(7, lvl + 1) else: if neigh == 3: new_board[i * height + j] = 0 else: new_board[i * height + j] = min(7, lvl + 1) self.board = new_board def all_dead(self): for i in xrange(size): if self.board[i] != 7: return False return True def show_board(self): for i in xrange(width): for j in xrange(height): rgb = self.color[self.value(i, j)] unicorn.set_pixel(i, j, rgb[0], rgb[1], rgb[2]) unicorn.show() life = GameOfLife() while not life.all_dead(): life.next_generation() life.show_board() time.sleep(0.05) ./examples/rainbow.py0000775000175000017500000000226414223621661016004 0ustar jawn-smithjawn-smith#!/usr/bin/env python import math import time import unicornhat as unicorn print("""Rainbow Displays a beautiful rainbow across your HAT/pHAT :D If you're using a Unicorn HAT and only half the screen lights up, edit this example and change 'unicorn.AUTO' to 'unicorn.HAT' below. """) unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) unicorn.brightness(0.5) width,height=unicorn.get_shape() print("Reticulating splines") time.sleep(.5) print("Enabled unicorn poop module!") time.sleep(.5) print("Pooping rainbows...") i = 0.0 offset = 30 while True: i = i + 0.3 for y in range(height): for x in range(width): r = (math.cos((x+i)/2.0) + math.cos((y+i)/2.0)) * 64.0 + 128.0 g = (math.sin((x+i)/1.5) + math.sin((y+i)/2.0)) * 64.0 + 128.0 b = (math.sin((x+i)/2.0) + math.cos((y+i)/1.5)) * 64.0 + 128.0 r = max(0, min(255, r + offset)) g = max(0, min(255, g + offset)) b = max(0, min(255, b + offset)) unicorn.set_pixel(x,y,int(r),int(g),int(b)) unicorn.show() time.sleep(0.01) ./documentation/0000775000175000017500000000000014223644616015022 5ustar jawn-smithjawn-smith./documentation/Function-reference.md0000664000175000017500000000606514223621661021067 0ustar jawn-smithjawn-smith #Unicorn HAT Function Reference Note: all of the functions detailed below are applicable to the Unicorn pHAT, but please check the next section for important information. ```python rotation( 90 ) ``` Set the rotation of your Unicorn HAT's output, can be one of 0, 90, 180 or 270 degrees. ```python brightness( 0.5 ) ``` Set the global brightness of Unicorn HAT. This defaults to 0.2 to save your eyes, but can be anywhere from 0.0 to 1.0. ```python clear() ``` Clears the buffer, setting all pixels to RGB 0,0,0. This won't update UnicornHAT until you call `show()` ```python off() ``` Clears the buffer and updates Unicorn HAT immediately by calling clear, and then show for you. ```python set_pixel(x, y, r, g, b) ``` Sets the pixel at x,y to colour r,g,b. The x and y values should be between 0 and 7, and r, g, b between 0 and 255. The actual brightness value displayed will depend upon the global brightness. ```python get_pixel(x, y) ``` Returns the colour of the pixel at x, y as a tuple of 3 items from 0 to 255. ```python set_pixels(pixels) ``` Accepts a 2d list of pixels of dimensions 8:8 ( [[0]*8]*8 ). Can be used to set the whole buffer in one go from a numpy array. ```python get_pixels() ``` Gets the whole pixel buffer as a 2d list of dimensions 8:8. ```python show() ``` Updates the Unicorn HAT with the current buffer. The buffer contains all pixel data that you have drawn with the set_pixel or set_pixels methods. ```python set_layout(unicorn.HAT) ``` Enforces the pixel mapping required for the Unicorn HAT. This is the default, so in nnormal circumstances only needed if you need to reset the layout after using the Unicorn pHAT. #Unicorn pHAT Function Reference ```python set_layout(unicorn.PHAT) ``` Enforces the pixel mapping required for the Unicorn pHAT. It must be called at the start of your routine for pixel coordinates to be handled correctly. ```python rotation( 180 ) ``` Set the rotation of your Unicorn pHAT's output. 180 will invert the display, i.e set the origin in the bottom right corner, looking at the PCB with the header at the top. O will reset the origin. It is not possible to swap the x and y axis. ```python set_pixel(x, y, r, g, b) ``` Sets the pixel at x,y to colour r,g,b. The x value should be between 0 and 7, the y value should be between 0 and 3. r, g, b must be between 0 and 255. The actual brightness value displayed will depend upon the global brightness. Note that for compatibility with Unicorn HAT y values between 4 and 7 will be accepted but wrap around the range. In other words they are technically acceptable but should be avoided when writing programs designed for the pHAT. All other functions detailed in the HAT sections are otherwise valid and identical../projects/0000775000175000017500000000000014223621661013775 5ustar jawn-smithjawn-smith./projects/unicornpaint/0000775000175000017500000000000014223621661016506 5ustar jawn-smithjawn-smith./projects/unicornpaint/static/0000775000175000017500000000000014223621661017775 5ustar jawn-smithjawn-smith./projects/unicornpaint/static/font-awesome.min.css0000664000175000017500000005274014223621661023705 0ustar jawn-smithjawn-smith/*! * Font Awesome 4.2.0 by @davegandy - http://fontawesome.io - @fontawesome * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) */@font-face{font-family:'FontAwesome';src:url('../fonts/fontawesome-webfont.eot?v=4.2.0');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=4.2.0') format('embedded-opentype'),url('../fonts/fontawesome-webfont.woff?v=4.2.0') format('woff'),url('../fonts/fontawesome-webfont.ttf?v=4.2.0') format('truetype'),url('../fonts/fontawesome-webfont.svg?v=4.2.0#fontawesomeregular') format('svg');font-weight:normal;font-style:normal}.fa{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.33333333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.28571429em;text-align:center}.fa-ul{padding-left:0;margin-left:2.14285714em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.14285714em;width:2.14285714em;top:.14285714em;text-align:center}.fa-li.fa-lg{left:-1.85714286em}.fa-border{padding:.2em .25em .15em;border:solid .08em #eee;border-radius:.1em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left{margin-right:.3em}.fa.pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=1);-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1);-webkit-transform:scale(-1, 1);-ms-transform:scale(-1, 1);transform:scale(-1, 1)}.fa-flip-vertical{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1);-webkit-transform:scale(1, -1);-ms-transform:scale(1, -1);transform:scale(1, -1)}:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-flip-horizontal,:root .fa-flip-vertical{filter:none}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:"\f000"}.fa-music:before{content:"\f001"}.fa-search:before{content:"\f002"}.fa-envelope-o:before{content:"\f003"}.fa-heart:before{content:"\f004"}.fa-star:before{content:"\f005"}.fa-star-o:before{content:"\f006"}.fa-user:before{content:"\f007"}.fa-film:before{content:"\f008"}.fa-th-large:before{content:"\f009"}.fa-th:before{content:"\f00a"}.fa-th-list:before{content:"\f00b"}.fa-check:before{content:"\f00c"}.fa-remove:before,.fa-close:before,.fa-times:before{content:"\f00d"}.fa-search-plus:before{content:"\f00e"}.fa-search-minus:before{content:"\f010"}.fa-power-off:before{content:"\f011"}.fa-signal:before{content:"\f012"}.fa-gear:before,.fa-cog:before{content:"\f013"}.fa-trash-o:before{content:"\f014"}.fa-home:before{content:"\f015"}.fa-file-o:before{content:"\f016"}.fa-clock-o:before{content:"\f017"}.fa-road:before{content:"\f018"}.fa-download:before{content:"\f019"}.fa-arrow-circle-o-down:before{content:"\f01a"}.fa-arrow-circle-o-up:before{content:"\f01b"}.fa-inbox:before{content:"\f01c"}.fa-play-circle-o:before{content:"\f01d"}.fa-rotate-right:before,.fa-repeat:before{content:"\f01e"}.fa-refresh:before{content:"\f021"}.fa-list-alt:before{content:"\f022"}.fa-lock:before{content:"\f023"}.fa-flag:before{content:"\f024"}.fa-headphones:before{content:"\f025"}.fa-volume-off:before{content:"\f026"}.fa-volume-down:before{content:"\f027"}.fa-volume-up:before{content:"\f028"}.fa-qrcode:before{content:"\f029"}.fa-barcode:before{content:"\f02a"}.fa-tag:before{content:"\f02b"}.fa-tags:before{content:"\f02c"}.fa-book:before{content:"\f02d"}.fa-bookmark:before{content:"\f02e"}.fa-print:before{content:"\f02f"}.fa-camera:before{content:"\f030"}.fa-font:before{content:"\f031"}.fa-bold:before{content:"\f032"}.fa-italic:before{content:"\f033"}.fa-text-height:before{content:"\f034"}.fa-text-width:before{content:"\f035"}.fa-align-left:before{content:"\f036"}.fa-align-center:before{content:"\f037"}.fa-align-right:before{content:"\f038"}.fa-align-justify:before{content:"\f039"}.fa-list:before{content:"\f03a"}.fa-dedent:before,.fa-outdent:before{content:"\f03b"}.fa-indent:before{content:"\f03c"}.fa-video-camera:before{content:"\f03d"}.fa-photo:before,.fa-image:before,.fa-picture-o:before{content:"\f03e"}.fa-pencil:before{content:"\f040"}.fa-map-marker:before{content:"\f041"}.fa-adjust:before{content:"\f042"}.fa-tint:before{content:"\f043"}.fa-edit:before,.fa-pencil-square-o:before{content:"\f044"}.fa-share-square-o:before{content:"\f045"}.fa-check-square-o:before{content:"\f046"}.fa-arrows:before{content:"\f047"}.fa-step-backward:before{content:"\f048"}.fa-fast-backward:before{content:"\f049"}.fa-backward:before{content:"\f04a"}.fa-play:before{content:"\f04b"}.fa-pause:before{content:"\f04c"}.fa-stop:before{content:"\f04d"}.fa-forward:before{content:"\f04e"}.fa-fast-forward:before{content:"\f050"}.fa-step-forward:before{content:"\f051"}.fa-eject:before{content:"\f052"}.fa-chevron-left:before{content:"\f053"}.fa-chevron-right:before{content:"\f054"}.fa-plus-circle:before{content:"\f055"}.fa-minus-circle:before{content:"\f056"}.fa-times-circle:before{content:"\f057"}.fa-check-circle:before{content:"\f058"}.fa-question-circle:before{content:"\f059"}.fa-info-circle:before{content:"\f05a"}.fa-crosshairs:before{content:"\f05b"}.fa-times-circle-o:before{content:"\f05c"}.fa-check-circle-o:before{content:"\f05d"}.fa-ban:before{content:"\f05e"}.fa-arrow-left:before{content:"\f060"}.fa-arrow-right:before{content:"\f061"}.fa-arrow-up:before{content:"\f062"}.fa-arrow-down:before{content:"\f063"}.fa-mail-forward:before,.fa-share:before{content:"\f064"}.fa-expand:before{content:"\f065"}.fa-compress:before{content:"\f066"}.fa-plus:before{content:"\f067"}.fa-minus:before{content:"\f068"}.fa-asterisk:before{content:"\f069"}.fa-exclamation-circle:before{content:"\f06a"}.fa-gift:before{content:"\f06b"}.fa-leaf:before{content:"\f06c"}.fa-fire:before{content:"\f06d"}.fa-eye:before{content:"\f06e"}.fa-eye-slash:before{content:"\f070"}.fa-warning:before,.fa-exclamation-triangle:before{content:"\f071"}.fa-plane:before{content:"\f072"}.fa-calendar:before{content:"\f073"}.fa-random:before{content:"\f074"}.fa-comment:before{content:"\f075"}.fa-magnet:before{content:"\f076"}.fa-chevron-up:before{content:"\f077"}.fa-chevron-down:before{content:"\f078"}.fa-retweet:before{content:"\f079"}.fa-shopping-cart:before{content:"\f07a"}.fa-folder:before{content:"\f07b"}.fa-folder-open:before{content:"\f07c"}.fa-arrows-v:before{content:"\f07d"}.fa-arrows-h:before{content:"\f07e"}.fa-bar-chart-o:before,.fa-bar-chart:before{content:"\f080"}.fa-twitter-square:before{content:"\f081"}.fa-facebook-square:before{content:"\f082"}.fa-camera-retro:before{content:"\f083"}.fa-key:before{content:"\f084"}.fa-gears:before,.fa-cogs:before{content:"\f085"}.fa-comments:before{content:"\f086"}.fa-thumbs-o-up:before{content:"\f087"}.fa-thumbs-o-down:before{content:"\f088"}.fa-star-half:before{content:"\f089"}.fa-heart-o:before{content:"\f08a"}.fa-sign-out:before{content:"\f08b"}.fa-linkedin-square:before{content:"\f08c"}.fa-thumb-tack:before{content:"\f08d"}.fa-external-link:before{content:"\f08e"}.fa-sign-in:before{content:"\f090"}.fa-trophy:before{content:"\f091"}.fa-github-square:before{content:"\f092"}.fa-upload:before{content:"\f093"}.fa-lemon-o:before{content:"\f094"}.fa-phone:before{content:"\f095"}.fa-square-o:before{content:"\f096"}.fa-bookmark-o:before{content:"\f097"}.fa-phone-square:before{content:"\f098"}.fa-twitter:before{content:"\f099"}.fa-facebook:before{content:"\f09a"}.fa-github:before{content:"\f09b"}.fa-unlock:before{content:"\f09c"}.fa-credit-card:before{content:"\f09d"}.fa-rss:before{content:"\f09e"}.fa-hdd-o:before{content:"\f0a0"}.fa-bullhorn:before{content:"\f0a1"}.fa-bell:before{content:"\f0f3"}.fa-certificate:before{content:"\f0a3"}.fa-hand-o-right:before{content:"\f0a4"}.fa-hand-o-left:before{content:"\f0a5"}.fa-hand-o-up:before{content:"\f0a6"}.fa-hand-o-down:before{content:"\f0a7"}.fa-arrow-circle-left:before{content:"\f0a8"}.fa-arrow-circle-right:before{content:"\f0a9"}.fa-arrow-circle-up:before{content:"\f0aa"}.fa-arrow-circle-down:before{content:"\f0ab"}.fa-globe:before{content:"\f0ac"}.fa-wrench:before{content:"\f0ad"}.fa-tasks:before{content:"\f0ae"}.fa-filter:before{content:"\f0b0"}.fa-briefcase:before{content:"\f0b1"}.fa-arrows-alt:before{content:"\f0b2"}.fa-group:before,.fa-users:before{content:"\f0c0"}.fa-chain:before,.fa-link:before{content:"\f0c1"}.fa-cloud:before{content:"\f0c2"}.fa-flask:before{content:"\f0c3"}.fa-cut:before,.fa-scissors:before{content:"\f0c4"}.fa-copy:before,.fa-files-o:before{content:"\f0c5"}.fa-paperclip:before{content:"\f0c6"}.fa-save:before,.fa-floppy-o:before{content:"\f0c7"}.fa-square:before{content:"\f0c8"}.fa-navicon:before,.fa-reorder:before,.fa-bars:before{content:"\f0c9"}.fa-list-ul:before{content:"\f0ca"}.fa-list-ol:before{content:"\f0cb"}.fa-strikethrough:before{content:"\f0cc"}.fa-underline:before{content:"\f0cd"}.fa-table:before{content:"\f0ce"}.fa-magic:before{content:"\f0d0"}.fa-truck:before{content:"\f0d1"}.fa-pinterest:before{content:"\f0d2"}.fa-pinterest-square:before{content:"\f0d3"}.fa-google-plus-square:before{content:"\f0d4"}.fa-google-plus:before{content:"\f0d5"}.fa-money:before{content:"\f0d6"}.fa-caret-down:before{content:"\f0d7"}.fa-caret-up:before{content:"\f0d8"}.fa-caret-left:before{content:"\f0d9"}.fa-caret-right:before{content:"\f0da"}.fa-columns:before{content:"\f0db"}.fa-unsorted:before,.fa-sort:before{content:"\f0dc"}.fa-sort-down:before,.fa-sort-desc:before{content:"\f0dd"}.fa-sort-up:before,.fa-sort-asc:before{content:"\f0de"}.fa-envelope:before{content:"\f0e0"}.fa-linkedin:before{content:"\f0e1"}.fa-rotate-left:before,.fa-undo:before{content:"\f0e2"}.fa-legal:before,.fa-gavel:before{content:"\f0e3"}.fa-dashboard:before,.fa-tachometer:before{content:"\f0e4"}.fa-comment-o:before{content:"\f0e5"}.fa-comments-o:before{content:"\f0e6"}.fa-flash:before,.fa-bolt:before{content:"\f0e7"}.fa-sitemap:before{content:"\f0e8"}.fa-umbrella:before{content:"\f0e9"}.fa-paste:before,.fa-clipboard:before{content:"\f0ea"}.fa-lightbulb-o:before{content:"\f0eb"}.fa-exchange:before{content:"\f0ec"}.fa-cloud-download:before{content:"\f0ed"}.fa-cloud-upload:before{content:"\f0ee"}.fa-user-md:before{content:"\f0f0"}.fa-stethoscope:before{content:"\f0f1"}.fa-suitcase:before{content:"\f0f2"}.fa-bell-o:before{content:"\f0a2"}.fa-coffee:before{content:"\f0f4"}.fa-cutlery:before{content:"\f0f5"}.fa-file-text-o:before{content:"\f0f6"}.fa-building-o:before{content:"\f0f7"}.fa-hospital-o:before{content:"\f0f8"}.fa-ambulance:before{content:"\f0f9"}.fa-medkit:before{content:"\f0fa"}.fa-fighter-jet:before{content:"\f0fb"}.fa-beer:before{content:"\f0fc"}.fa-h-square:before{content:"\f0fd"}.fa-plus-square:before{content:"\f0fe"}.fa-angle-double-left:before{content:"\f100"}.fa-angle-double-right:before{content:"\f101"}.fa-angle-double-up:before{content:"\f102"}.fa-angle-double-down:before{content:"\f103"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"}.fa-angle-up:before{content:"\f106"}.fa-angle-down:before{content:"\f107"}.fa-desktop:before{content:"\f108"}.fa-laptop:before{content:"\f109"}.fa-tablet:before{content:"\f10a"}.fa-mobile-phone:before,.fa-mobile:before{content:"\f10b"}.fa-circle-o:before{content:"\f10c"}.fa-quote-left:before{content:"\f10d"}.fa-quote-right:before{content:"\f10e"}.fa-spinner:before{content:"\f110"}.fa-circle:before{content:"\f111"}.fa-mail-reply:before,.fa-reply:before{content:"\f112"}.fa-github-alt:before{content:"\f113"}.fa-folder-o:before{content:"\f114"}.fa-folder-open-o:before{content:"\f115"}.fa-smile-o:before{content:"\f118"}.fa-frown-o:before{content:"\f119"}.fa-meh-o:before{content:"\f11a"}.fa-gamepad:before{content:"\f11b"}.fa-keyboard-o:before{content:"\f11c"}.fa-flag-o:before{content:"\f11d"}.fa-flag-checkered:before{content:"\f11e"}.fa-terminal:before{content:"\f120"}.fa-code:before{content:"\f121"}.fa-mail-reply-all:before,.fa-reply-all:before{content:"\f122"}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:"\f123"}.fa-location-arrow:before{content:"\f124"}.fa-crop:before{content:"\f125"}.fa-code-fork:before{content:"\f126"}.fa-unlink:before,.fa-chain-broken:before{content:"\f127"}.fa-question:before{content:"\f128"}.fa-info:before{content:"\f129"}.fa-exclamation:before{content:"\f12a"}.fa-superscript:before{content:"\f12b"}.fa-subscript:before{content:"\f12c"}.fa-eraser:before{content:"\f12d"}.fa-puzzle-piece:before{content:"\f12e"}.fa-microphone:before{content:"\f130"}.fa-microphone-slash:before{content:"\f131"}.fa-shield:before{content:"\f132"}.fa-calendar-o:before{content:"\f133"}.fa-fire-extinguisher:before{content:"\f134"}.fa-rocket:before{content:"\f135"}.fa-maxcdn:before{content:"\f136"}.fa-chevron-circle-left:before{content:"\f137"}.fa-chevron-circle-right:before{content:"\f138"}.fa-chevron-circle-up:before{content:"\f139"}.fa-chevron-circle-down:before{content:"\f13a"}.fa-html5:before{content:"\f13b"}.fa-css3:before{content:"\f13c"}.fa-anchor:before{content:"\f13d"}.fa-unlock-alt:before{content:"\f13e"}.fa-bullseye:before{content:"\f140"}.fa-ellipsis-h:before{content:"\f141"}.fa-ellipsis-v:before{content:"\f142"}.fa-rss-square:before{content:"\f143"}.fa-play-circle:before{content:"\f144"}.fa-ticket:before{content:"\f145"}.fa-minus-square:before{content:"\f146"}.fa-minus-square-o:before{content:"\f147"}.fa-level-up:before{content:"\f148"}.fa-level-down:before{content:"\f149"}.fa-check-square:before{content:"\f14a"}.fa-pencil-square:before{content:"\f14b"}.fa-external-link-square:before{content:"\f14c"}.fa-share-square:before{content:"\f14d"}.fa-compass:before{content:"\f14e"}.fa-toggle-down:before,.fa-caret-square-o-down:before{content:"\f150"}.fa-toggle-up:before,.fa-caret-square-o-up:before{content:"\f151"}.fa-toggle-right:before,.fa-caret-square-o-right:before{content:"\f152"}.fa-euro:before,.fa-eur:before{content:"\f153"}.fa-gbp:before{content:"\f154"}.fa-dollar:before,.fa-usd:before{content:"\f155"}.fa-rupee:before,.fa-inr:before{content:"\f156"}.fa-cny:before,.fa-rmb:before,.fa-yen:before,.fa-jpy:before{content:"\f157"}.fa-ruble:before,.fa-rouble:before,.fa-rub:before{content:"\f158"}.fa-won:before,.fa-krw:before{content:"\f159"}.fa-bitcoin:before,.fa-btc:before{content:"\f15a"}.fa-file:before{content:"\f15b"}.fa-file-text:before{content:"\f15c"}.fa-sort-alpha-asc:before{content:"\f15d"}.fa-sort-alpha-desc:before{content:"\f15e"}.fa-sort-amount-asc:before{content:"\f160"}.fa-sort-amount-desc:before{content:"\f161"}.fa-sort-numeric-asc:before{content:"\f162"}.fa-sort-numeric-desc:before{content:"\f163"}.fa-thumbs-up:before{content:"\f164"}.fa-thumbs-down:before{content:"\f165"}.fa-youtube-square:before{content:"\f166"}.fa-youtube:before{content:"\f167"}.fa-xing:before{content:"\f168"}.fa-xing-square:before{content:"\f169"}.fa-youtube-play:before{content:"\f16a"}.fa-dropbox:before{content:"\f16b"}.fa-stack-overflow:before{content:"\f16c"}.fa-instagram:before{content:"\f16d"}.fa-flickr:before{content:"\f16e"}.fa-adn:before{content:"\f170"}.fa-bitbucket:before{content:"\f171"}.fa-bitbucket-square:before{content:"\f172"}.fa-tumblr:before{content:"\f173"}.fa-tumblr-square:before{content:"\f174"}.fa-long-arrow-down:before{content:"\f175"}.fa-long-arrow-up:before{content:"\f176"}.fa-long-arrow-left:before{content:"\f177"}.fa-long-arrow-right:before{content:"\f178"}.fa-apple:before{content:"\f179"}.fa-windows:before{content:"\f17a"}.fa-android:before{content:"\f17b"}.fa-linux:before{content:"\f17c"}.fa-dribbble:before{content:"\f17d"}.fa-skype:before{content:"\f17e"}.fa-foursquare:before{content:"\f180"}.fa-trello:before{content:"\f181"}.fa-female:before{content:"\f182"}.fa-male:before{content:"\f183"}.fa-gittip:before{content:"\f184"}.fa-sun-o:before{content:"\f185"}.fa-moon-o:before{content:"\f186"}.fa-archive:before{content:"\f187"}.fa-bug:before{content:"\f188"}.fa-vk:before{content:"\f189"}.fa-weibo:before{content:"\f18a"}.fa-renren:before{content:"\f18b"}.fa-pagelines:before{content:"\f18c"}.fa-stack-exchange:before{content:"\f18d"}.fa-arrow-circle-o-right:before{content:"\f18e"}.fa-arrow-circle-o-left:before{content:"\f190"}.fa-toggle-left:before,.fa-caret-square-o-left:before{content:"\f191"}.fa-dot-circle-o:before{content:"\f192"}.fa-wheelchair:before{content:"\f193"}.fa-vimeo-square:before{content:"\f194"}.fa-turkish-lira:before,.fa-try:before{content:"\f195"}.fa-plus-square-o:before{content:"\f196"}.fa-space-shuttle:before{content:"\f197"}.fa-slack:before{content:"\f198"}.fa-envelope-square:before{content:"\f199"}.fa-wordpress:before{content:"\f19a"}.fa-openid:before{content:"\f19b"}.fa-institution:before,.fa-bank:before,.fa-university:before{content:"\f19c"}.fa-mortar-board:before,.fa-graduation-cap:before{content:"\f19d"}.fa-yahoo:before{content:"\f19e"}.fa-google:before{content:"\f1a0"}.fa-reddit:before{content:"\f1a1"}.fa-reddit-square:before{content:"\f1a2"}.fa-stumbleupon-circle:before{content:"\f1a3"}.fa-stumbleupon:before{content:"\f1a4"}.fa-delicious:before{content:"\f1a5"}.fa-digg:before{content:"\f1a6"}.fa-pied-piper:before{content:"\f1a7"}.fa-pied-piper-alt:before{content:"\f1a8"}.fa-drupal:before{content:"\f1a9"}.fa-joomla:before{content:"\f1aa"}.fa-language:before{content:"\f1ab"}.fa-fax:before{content:"\f1ac"}.fa-building:before{content:"\f1ad"}.fa-child:before{content:"\f1ae"}.fa-paw:before{content:"\f1b0"}.fa-spoon:before{content:"\f1b1"}.fa-cube:before{content:"\f1b2"}.fa-cubes:before{content:"\f1b3"}.fa-behance:before{content:"\f1b4"}.fa-behance-square:before{content:"\f1b5"}.fa-steam:before{content:"\f1b6"}.fa-steam-square:before{content:"\f1b7"}.fa-recycle:before{content:"\f1b8"}.fa-automobile:before,.fa-car:before{content:"\f1b9"}.fa-cab:before,.fa-taxi:before{content:"\f1ba"}.fa-tree:before{content:"\f1bb"}.fa-spotify:before{content:"\f1bc"}.fa-deviantart:before{content:"\f1bd"}.fa-soundcloud:before{content:"\f1be"}.fa-database:before{content:"\f1c0"}.fa-file-pdf-o:before{content:"\f1c1"}.fa-file-word-o:before{content:"\f1c2"}.fa-file-excel-o:before{content:"\f1c3"}.fa-file-powerpoint-o:before{content:"\f1c4"}.fa-file-photo-o:before,.fa-file-picture-o:before,.fa-file-image-o:before{content:"\f1c5"}.fa-file-zip-o:before,.fa-file-archive-o:before{content:"\f1c6"}.fa-file-sound-o:before,.fa-file-audio-o:before{content:"\f1c7"}.fa-file-movie-o:before,.fa-file-video-o:before{content:"\f1c8"}.fa-file-code-o:before{content:"\f1c9"}.fa-vine:before{content:"\f1ca"}.fa-codepen:before{content:"\f1cb"}.fa-jsfiddle:before{content:"\f1cc"}.fa-life-bouy:before,.fa-life-buoy:before,.fa-life-saver:before,.fa-support:before,.fa-life-ring:before{content:"\f1cd"}.fa-circle-o-notch:before{content:"\f1ce"}.fa-ra:before,.fa-rebel:before{content:"\f1d0"}.fa-ge:before,.fa-empire:before{content:"\f1d1"}.fa-git-square:before{content:"\f1d2"}.fa-git:before{content:"\f1d3"}.fa-hacker-news:before{content:"\f1d4"}.fa-tencent-weibo:before{content:"\f1d5"}.fa-qq:before{content:"\f1d6"}.fa-wechat:before,.fa-weixin:before{content:"\f1d7"}.fa-send:before,.fa-paper-plane:before{content:"\f1d8"}.fa-send-o:before,.fa-paper-plane-o:before{content:"\f1d9"}.fa-history:before{content:"\f1da"}.fa-circle-thin:before{content:"\f1db"}.fa-header:before{content:"\f1dc"}.fa-paragraph:before{content:"\f1dd"}.fa-sliders:before{content:"\f1de"}.fa-share-alt:before{content:"\f1e0"}.fa-share-alt-square:before{content:"\f1e1"}.fa-bomb:before{content:"\f1e2"}.fa-soccer-ball-o:before,.fa-futbol-o:before{content:"\f1e3"}.fa-tty:before{content:"\f1e4"}.fa-binoculars:before{content:"\f1e5"}.fa-plug:before{content:"\f1e6"}.fa-slideshare:before{content:"\f1e7"}.fa-twitch:before{content:"\f1e8"}.fa-yelp:before{content:"\f1e9"}.fa-newspaper-o:before{content:"\f1ea"}.fa-wifi:before{content:"\f1eb"}.fa-calculator:before{content:"\f1ec"}.fa-paypal:before{content:"\f1ed"}.fa-google-wallet:before{content:"\f1ee"}.fa-cc-visa:before{content:"\f1f0"}.fa-cc-mastercard:before{content:"\f1f1"}.fa-cc-discover:before{content:"\f1f2"}.fa-cc-amex:before{content:"\f1f3"}.fa-cc-paypal:before{content:"\f1f4"}.fa-cc-stripe:before{content:"\f1f5"}.fa-bell-slash:before{content:"\f1f6"}.fa-bell-slash-o:before{content:"\f1f7"}.fa-trash:before{content:"\f1f8"}.fa-copyright:before{content:"\f1f9"}.fa-at:before{content:"\f1fa"}.fa-eyedropper:before{content:"\f1fb"}.fa-paint-brush:before{content:"\f1fc"}.fa-birthday-cake:before{content:"\f1fd"}.fa-area-chart:before{content:"\f1fe"}.fa-pie-chart:before{content:"\f200"}.fa-line-chart:before{content:"\f201"}.fa-lastfm:before{content:"\f202"}.fa-lastfm-square:before{content:"\f203"}.fa-toggle-off:before{content:"\f204"}.fa-toggle-on:before{content:"\f205"}.fa-bicycle:before{content:"\f206"}.fa-bus:before{content:"\f207"}.fa-ioxhost:before{content:"\f208"}.fa-angellist:before{content:"\f209"}.fa-cc:before{content:"\f20a"}.fa-shekel:before,.fa-sheqel:before,.fa-ils:before{content:"\f20b"}.fa-meanpath:before{content:"\f20c"}./projects/unicornpaint/static/unicorn-paint.js0000664000175000017500000001222414223621661023122 0ustar jawn-smithjawn-smithvar md = false; var color = tinycolor('#840000'); $(document).ready(function(){ $.ajaxSetup({ cache: false }); $('.unicorn').draggable({ handle: "h1" }); $(document) .on('mousedown',function(e){md=true;}) .on('mouseup',function(e){md=false;}); $('table').on('dragstart',function(e){ e.preventDefault(); return false; }); $('.tools li').on('click',function(){ switch($(this).index()){ case 6: clear(); break; case 7: save(); break; default: $('.tools li').removeClass('selected'); $(this).addClass('selected'); break; } }); $('.palette li').on('click',function(){ $('.palette li').removeClass('selected'); $(this).addClass('selected'); $('.current').css('background-color', current_color().toRgbString() ); $('.mc').trigger("colorpickersliders.updateColor", current_color().toHexString()); }).each(function(){ $(this).data('default', $(this).css('background-color')); }); function current_color(){ return color; } function handle_tool(obj, is_click){ switch($('.tools li.selected').index()){ case 0: //'paint': paint(obj); break; case 1: // Fill if( is_click ) fill(obj); break; case 2: // Erase update_pixel(obj, tinycolor('#000000')); break; case 3: //'pick': pick(obj); break; case 4: //'lighten': lighten(obj); break; case 5: //'darken': darken(obj); break; } } var fill_target = null; var fill_stack = []; function fill(obj){ fill_target = tinycolor($(obj).css('background-color')).toRgbString(); if( fill_target == current_color().toRgbString ){ return false; } console.log('Fill Target',fill_target); console.log('Fill With',current_color()); do_fill(obj); while(fill_stack.length > 0){ pixel = fill_stack.pop(); do_fill(pixel); } } function is_target_color(obj){ return ( tinycolor($(obj).css('background-color')).toRgbString() == fill_target); } function do_fill(obj){ obj = $(obj); if( is_target_color(obj) ){ update_pixel(obj, current_color()); var r = obj.next('td'); var l = obj.prev('td'); var u = obj.parent().prev('tr').find('td:eq(' + obj.index() + ')'); var d = obj.parent().next('tr').find('td:eq(' + obj.index() + ')'); if( r.length && is_target_color(r[0]) ) fill_stack.push(r[0]); if( l.length && is_target_color(l[0]) ) fill_stack.push(l[0]); if( u.length && is_target_color(u[0]) ) fill_stack.push(u[0]); if( d.length && is_target_color(d[0]) ) fill_stack.push(d[0]); } } function save(){ var filename = prompt('Please enter a filename', 'mypaint'); filename = filename.replace(/[^a-z0-9]/gi, '_').toLowerCase(); $.get('/save/' + filename); alert('Saved into saves/' + filename + '.py, \nRun with "sudo saves/' + filename + '.py"'); } function clear(){ $('td').css('background-color','rgb(0,0,0)').data('changed',false); $.get('/clear'); $.get('/show'); } function lighten(obj){ var rgb = tinycolor($(obj).css('background-color')).toRgb(); update_pixel(obj, tinycolor({ r: rgb.r + 2, g: rgb.g + 2, b: rgb.b + 2 })); } function darken(obj){ var rgb = tinycolor($(obj).css('background-color')).toRgb(); update_pixel(obj, tinycolor({ r: rgb.r - 2, g: rgb.g - 2, b: rgb.b - 2 })); } /* function set_color(hex){ $('.palette li.selected').css('background-color', rgb_string(rgb)); $('.current').css('background-color',rgb_string(rgb)); } */ function pick(obj){ var col = tinycolor($(obj).css('background-color')); $('.mc').trigger("colorpickersliders.updateColor", col.toHexString()); } function update_pixel(obj, col){ var bgcol = tinycolor($(obj).css('background-color')); if( col.toRgbString() != bgcol.toRgbString() ){ $(obj) .data('changed', true) .css('background-color',col.toRgbString()); } } function update_pixels(){ var changed = false; $('td').each(function( index, obj ){ if( $(obj).data('changed') ){ $(obj).data('changed',false); changed = true; var x = $(this).index(); var y = $(this).parent().index(); var col = tinycolor($(obj).css('background-color')).toRgb(); var data = [x,y,col.r,col.g,col.b]; $.get('/pixel/' + data.join('/')); } }); if(changed){ $.get('/show'); } } function paint(obj){ update_pixel(obj, current_color()); } $('table td').on('click',function(){ handle_tool(this, true); }); $('table td').on('mousemove',function(){ if(!md) return false; handle_tool(this, false); }) swatches = [ 'rgb(0,0,0)','rgb(132,0,0)','rgb(0,132,0)','rgb(132,132,0)','rgb(0,0,132)','rgb(132,0,132)','rgb(0,132,132)','rgb(132,132,132)', 'rgb(198,198,198)','rgb(255,0,0)','rgb(0,255,0)','rgb(255,255,0)','rgb(0,0,255)','rgb(255,0,255)','rgb(0,255,255)','rgb(255,255,255)' ]; $('.mc').ColorPickerSliders({ flat: true, previewformat: 'hex', color: current_color(), labels: { preview: '', hslhue: 'Hue', hslsaturation: 'Saturation', hsllightness: 'Lightness' }, swatches: swatches, order: { hsl: 1, preview: 2 }, onchange: function(obj, c){ color = c.tiny; } }); $.get('/clear'); $.get('/show'); var update = setInterval(update_pixels, 50); }); ./projects/unicornpaint/static/jquery-ui.min.js0000664000175000017500000067536314223621661023073 0ustar jawn-smithjawn-smith/*! jQuery UI - v1.10.1 - 2013-02-15 * http://jqueryui.com * Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.effect.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js, jquery.ui.menu.js, jquery.ui.position.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.tooltip.js * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ (function(e,t){function i(t,n){var r,i,o,u=t.nodeName.toLowerCase();return"area"===u?(r=t.parentNode,i=r.name,!t.href||!i||r.nodeName.toLowerCase()!=="map"?!1:(o=e("img[usemap=#"+i+"]")[0],!!o&&s(o))):(/input|select|textarea|button|object/.test(u)?!t.disabled:"a"===u?t.href||n:n)&&s(t)}function s(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return e.css(this,"visibility")==="hidden"}).length}var n=0,r=/^ui-id-\d+$/;e.ui=e.ui||{};if(e.ui.version)return;e.extend(e.ui,{version:"1.10.1",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({_focus:e.fn.focus,focus:function(t,n){return typeof t=="number"?this.each(function(){var r=this;setTimeout(function(){e(r).focus(),n&&n.call(r)},t)}):this._focus.apply(this,arguments)},scrollParent:function(){var t;return e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?t=this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):t=this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(n){if(n!==t)return this.css("zIndex",n);if(this.length){var r=e(this[0]),i,s;while(r.length&&r[0]!==document){i=r.css("position");if(i==="absolute"||i==="relative"||i==="fixed"){s=parseInt(r.css("zIndex"),10);if(!isNaN(s)&&s!==0)return s}r=r.parent()}}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++n)})},removeUniqueId:function(){return this.each(function(){r.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(n){return!!e.data(n,t)}}):function(t,n,r){return!!e.data(t,r[3])},focusable:function(t){return i(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var n=e.attr(t,"tabindex"),r=isNaN(n);return(r||n>=0)&&i(t,!r)}}),e("").outerWidth(1).jquery||e.each(["Width","Height"],function(n,r){function u(t,n,r,s){return e.each(i,function(){n-=parseFloat(e.css(t,"padding"+this))||0,r&&(n-=parseFloat(e.css(t,"border"+this+"Width"))||0),s&&(n-=parseFloat(e.css(t,"margin"+this))||0)}),n}var i=r==="Width"?["Left","Right"]:["Top","Bottom"],s=r.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+r]=function(n){return n===t?o["inner"+r].call(this):this.each(function(){e(this).css(s,u(this,n)+"px")})},e.fn["outer"+r]=function(t,n){return typeof t!="number"?o["outer"+r].call(this,t):this.each(function(){e(this).css(s,u(this,t,!0,n)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}),e("").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(n){return arguments.length?t.call(this,e.camelCase(n)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.support.selectstart="onselectstart"in document.createElement("div"),e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),e.extend(e.ui,{plugin:{add:function(t,n,r){var i,s=e.ui[t].prototype;for(i in r)s.plugins[i]=s.plugins[i]||[],s.plugins[i].push([n,r[i]])},call:function(e,t,n){var r,i=e.plugins[t];if(!i||!e.element[0].parentNode||e.element[0].parentNode.nodeType===11)return;for(r=0;r0?!0:(t[r]=1,i=t[r]>0,t[r]=0,i)}})})(jQuery),function(e,t){var n=0,r=Array.prototype.slice,i=e.cleanData;e.cleanData=function(t){for(var n=0,r;(r=t[n])!=null;n++)try{e(r).triggerHandler("remove")}catch(s){}i(t)},e.widget=function(t,n,r){var i,s,o,u,a={},f=t.split(".")[0];t=t.split(".")[1],i=f+"-"+t,r||(r=n,n=e.Widget),e.expr[":"][i.toLowerCase()]=function(t){return!!e.data(t,i)},e[f]=e[f]||{},s=e[f][t],o=e[f][t]=function(e,t){if(!this._createWidget)return new o(e,t);arguments.length&&this._createWidget(e,t)},e.extend(o,s,{version:r.version,_proto:e.extend({},r),_childConstructors:[]}),u=new n,u.options=e.widget.extend({},u.options),e.each(r,function(t,r){if(!e.isFunction(r)){a[t]=r;return}a[t]=function(){var e=function(){return n.prototype[t].apply(this,arguments)},i=function(e){return n.prototype[t].apply(this,e)};return function(){var t=this._super,n=this._superApply,s;return this._super=e,this._superApply=i,s=r.apply(this,arguments),this._super=t,this._superApply=n,s}}()}),o.prototype=e.widget.extend(u,{widgetEventPrefix:s?u.widgetEventPrefix:t},a,{constructor:o,namespace:f,widgetName:t,widgetFullName:i}),s?(e.each(s._childConstructors,function(t,n){var r=n.prototype;e.widget(r.namespace+"."+r.widgetName,o,n._proto)}),delete s._childConstructors):n._childConstructors.push(o),e.widget.bridge(t,o)},e.widget.extend=function(n){var i=r.call(arguments,1),s=0,o=i.length,u,a;for(;s",options:{disabled:!1,create:null},_createWidget:function(t,r){r=e(r||this.defaultElement||this)[0],this.element=e(r),this.uuid=n++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=e.widget.extend({},this.options,this._getCreateOptions(),t),this.bindings=e(),this.hoverable=e(),this.focusable=e(),r!==this&&(e.data(r,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===r&&this.destroy()}}),this.document=e(r.style?r.ownerDocument:r.document||r),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(n,r){var i=n,s,o,u;if(arguments.length===0)return e.widget.extend({},this.options);if(typeof n=="string"){i={},s=n.split("."),n=s.shift();if(s.length){o=i[n]=e.widget.extend({},this.options[n]);for(u=0;u=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})}(jQuery),function(e,t){e.widget("ui.draggable",e.ui.mouse,{version:"1.10.1",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){this.options.helper==="original"&&!/^(?:r|a|f)/.test(this.element.css("position"))&&(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},_destroy:function(){this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy()},_mouseCapture:function(t){var n=this.options;return this.helper||n.disabled||e(t.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(t),this.handle?(e(n.iframeFix===!0?"iframe":n.iframeFix).each(function(){e("
").css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(e(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(t){var n=this.options;return this.helper=this._createHelper(t),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),e.ui.ddmanager&&(e.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,n.cursorAt&&this._adjustOffsetFromHelper(n.cursorAt),n.containment&&this._setContainment(),this._trigger("start",t)===!1?(this._clear(),!1):(this._cacheHelperProportions(),e.ui.ddmanager&&!n.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this._mouseDrag(t,!0),e.ui.ddmanager&&e.ui.ddmanager.dragStart(this,t),!0)},_mouseDrag:function(t,n){this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute");if(!n){var r=this._uiHash();if(this._trigger("drag",t,r)===!1)return this._mouseUp({}),!1;this.position=r.position}if(!this.options.axis||this.options.axis!=="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!=="x")this.helper[0].style.top=this.position.top+"px";return e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),!1},_mouseStop:function(t){var n,r=this,i=!1,s=!1;e.ui.ddmanager&&!this.options.dropBehaviour&&(s=e.ui.ddmanager.drop(this,t)),this.dropped&&(s=this.dropped,this.dropped=!1),n=this.element[0];while(n&&(n=n.parentNode))n===document&&(i=!0);return!i&&this.options.helper==="original"?!1:(this.options.revert==="invalid"&&!s||this.options.revert==="valid"&&s||this.options.revert===!0||e.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?e(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){r._trigger("stop",t)!==!1&&r._clear()}):this._trigger("stop",t)!==!1&&this._clear(),!1)},_mouseUp:function(t){return e("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),e.ui.ddmanager&&e.ui.ddmanager.dragStop(this,t),e.ui.mouse.prototype._mouseUp.call(this,t)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(t){var n=!this.options.handle||!e(this.options.handle,this.element).length?!0:!1;return e(this.options.handle,this.element).find("*").addBack().each(function(){this===t.target&&(n=!0)}),n},_createHelper:function(t){var n=this.options,r=e.isFunction(n.helper)?e(n.helper.apply(this.element[0],[t])):n.helper==="clone"?this.element.clone().removeAttr("id"):this.element;return r.parents("body").length||r.appendTo(n.appendTo==="parent"?this.element[0].parentNode:n.appendTo),r[0]!==this.element[0]&&!/(fixed|absolute)/.test(r.css("position"))&&r.css("position","absolute"),r},_adjustOffsetFromHelper:function(t){typeof t=="string"&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();this.cssPosition==="absolute"&&this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()==="html"&&e.ui.ie)t={top:0,left:0};return{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition==="relative"){var e=this.element.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t,n,r,i=this.options;i.containment==="parent"&&(i.containment=this.helper[0].parentNode);if(i.containment==="document"||i.containment==="window")this.containment=[i.containment==="document"?0:e(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,i.containment==="document"?0:e(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(i.containment==="document"?0:e(window).scrollLeft())+e(i.containment==="document"?document:window).width()-this.helperProportions.width-this.margins.left,(i.containment==="document"?0:e(window).scrollTop())+(e(i.containment==="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(i.containment)&&i.containment.constructor!==Array){n=e(i.containment),r=n[0];if(!r)return;t=e(r).css("overflow")!=="hidden",this.containment=[(parseInt(e(r).css("borderLeftWidth"),10)||0)+(parseInt(e(r).css("paddingLeft"),10)||0),(parseInt(e(r).css("borderTopWidth"),10)||0)+(parseInt(e(r).css("paddingTop"),10)||0),(t?Math.max(r.scrollWidth,r.offsetWidth):r.offsetWidth)-(parseInt(e(r).css("borderLeftWidth"),10)||0)-(parseInt(e(r).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(t?Math.max(r.scrollHeight,r.offsetHeight):r.offsetHeight)-(parseInt(e(r).css("borderTopWidth"),10)||0)-(parseInt(e(r).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=n}else i.containment.constructor===Array&&(this.containment=i.containment)},_convertPositionTo:function(t,n){n||(n=this.position);var r=t==="absolute"?1:-1,i=this.cssPosition!=="absolute"||this.scrollParent[0]!==document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,s=/(html|body)/i.test(i[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-(this.cssPosition==="fixed"?-this.scrollParent.scrollTop():s?0:i.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-(this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():s?0:i.scrollLeft())*r}},_generatePosition:function(t){var n,r,i,s,o=this.options,u=this.cssPosition!=="absolute"||this.scrollParent[0]!==document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,a=/(html|body)/i.test(u[0].tagName),f=t.pageX,l=t.pageY;return this.originalPosition&&(this.containment&&(this.relative_container?(r=this.relative_container.offset(),n=[this.containment[0]+r.left,this.containment[1]+r.top,this.containment[2]+r.left,this.containment[3]+r.top]):n=this.containment,t.pageX-this.offset.click.leftn[2]&&(f=n[2]+this.offset.click.left),t.pageY-this.offset.click.top>n[3]&&(l=n[3]+this.offset.click.top)),o.grid&&(i=o.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/o.grid[1])*o.grid[1]:this.originalPageY,l=n?i-this.offset.click.top>=n[1]||i-this.offset.click.top>n[3]?i:i-this.offset.click.top>=n[1]?i-o.grid[1]:i+o.grid[1]:i,s=o.grid[0]?this.originalPageX+Math.round((f-this.originalPageX)/o.grid[0])*o.grid[0]:this.originalPageX,f=n?s-this.offset.click.left>=n[0]||s-this.offset.click.left>n[2]?s:s-this.offset.click.left>=n[0]?s-o.grid[0]:s+o.grid[0]:s)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition==="fixed"?-this.scrollParent.scrollTop():a?0:u.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():a?0:u.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]!==this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(t,n,r){return r=r||this._uiHash(),e.ui.plugin.call(this,t,[n,r]),t==="drag"&&(this.positionAbs=this._convertPositionTo("absolute")),e.Widget.prototype._trigger.call(this,t,n,r)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),e.ui.plugin.add("draggable","connectToSortable",{start:function(t,n){var r=e(this).data("ui-draggable"),i=r.options,s=e.extend({},n,{item:r.element});r.sortables=[],e(i.connectToSortable).each(function(){var n=e.data(this,"ui-sortable");n&&!n.options.disabled&&(r.sortables.push({instance:n,shouldRevert:n.options.revert}),n.refreshPositions(),n._trigger("activate",t,s))})},stop:function(t,n){var r=e(this).data("ui-draggable"),i=e.extend({},n,{item:r.element});e.each(r.sortables,function(){this.instance.isOver?(this.instance.isOver=0,r.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=!0),this.instance._mouseStop(t),this.instance.options.helper=this.instance.options._helper,r.options.helper==="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",t,i))})},drag:function(t,n){var r=e(this).data("ui-draggable"),i=this;e.each(r.sortables,function(){var s=!1,o=this;this.instance.positionAbs=r.positionAbs,this.instance.helperProportions=r.helperProportions,this.instance.offset.click=r.offset.click,this.instance._intersectsWith(this.instance.containerCache)&&(s=!0,e.each(r.sortables,function(){return this.instance.positionAbs=r.positionAbs,this.instance.helperProportions=r.helperProportions,this.instance.offset.click=r.offset.click,this!==o&&this.instance._intersectsWith(this.instance.containerCache)&&e.contains(o.instance.element[0],this.instance.element[0])&&(s=!1),s})),s?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=e(i).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return n.helper[0]},t.target=this.instance.currentItem[0],this.instance._mouseCapture(t,!0),this.instance._mouseStart(t,!0,!0),this.instance.offset.click.top=r.offset.click.top,this.instance.offset.click.left=r.offset.click.left,this.instance.offset.parent.left-=r.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=r.offset.parent.top-this.instance.offset.parent.top,r._trigger("toSortable",t),r.dropped=this.instance.element,r.currentItem=r.element,this.instance.fromOutside=r),this.instance.currentItem&&this.instance._mouseDrag(t)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",t,this.instance._uiHash(this.instance)),this.instance._mouseStop(t,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),r._trigger("fromSortable",t),r.dropped=!1)})}}),e.ui.plugin.add("draggable","cursor",{start:function(){var t=e("body"),n=e(this).data("ui-draggable").options;t.css("cursor")&&(n._cursor=t.css("cursor")),t.css("cursor",n.cursor)},stop:function(){var t=e(this).data("ui-draggable").options;t._cursor&&e("body").css("cursor",t._cursor)}}),e.ui.plugin.add("draggable","opacity",{start:function(t,n){var r=e(n.helper),i=e(this).data("ui-draggable").options;r.css("opacity")&&(i._opacity=r.css("opacity")),r.css("opacity",i.opacity)},stop:function(t,n){var r=e(this).data("ui-draggable").options;r._opacity&&e(n.helper).css("opacity",r._opacity)}}),e.ui.plugin.add("draggable","scroll",{start:function(){var t=e(this).data("ui-draggable");t.scrollParent[0]!==document&&t.scrollParent[0].tagName!=="HTML"&&(t.overflowOffset=t.scrollParent.offset())},drag:function(t){var n=e(this).data("ui-draggable"),r=n.options,i=!1;if(n.scrollParent[0]!==document&&n.scrollParent[0].tagName!=="HTML"){if(!r.axis||r.axis!=="x")n.overflowOffset.top+n.scrollParent[0].offsetHeight-t.pageY=0;c--){u=p.snapElements[c].left,a=u+p.snapElements[c].width,f=p.snapElements[c].top,l=f+p.snapElements[c].height;if(!(u-vt&&e=h&&a<=p||f>=h&&f<=p||ap)&&(o>=l&&o<=c||u>=l&&u<=c||oc);default:return!1}},e.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(t,n){var r,i,s=e.ui.ddmanager.droppables[t.options.scope]||[],o=n?n.type:null,u=(t.currentItem||t.element).find(":data(ui-droppable)").addBack();e:for(r=0;r").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.data("ui-resizable")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=u.handles||(e(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se");if(this.handles.constructor===String){this.handles==="all"&&(this.handles="n,e,s,w,se,sw,ne,nw"),t=this.handles.split(","),this.handles={};for(n=0;n"),i.css({zIndex:u.zIndex}),"se"===r&&i.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[r]=".ui-resizable-"+r,this.element.append(i)}this._renderAxis=function(t){var n,r,i,s;t=t||this.element;for(n in this.handles){this.handles[n].constructor===String&&(this.handles[n]=e(this.handles[n],this.element).show()),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)&&(r=e(this.handles[n],this.element),s=/sw|ne|nw|se|n|s/.test(n)?r.outerHeight():r.outerWidth(),i=["padding",/ne|nw|n/.test(n)?"Top":/se|sw|s/.test(n)?"Bottom":/^e$/.test(n)?"Right":"Left"].join(""),t.css(i,s),this._proportionallyResize());if(!e(this.handles[n]).length)continue}},this._renderAxis(this.element),this._handles=e(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){o.resizing||(this.className&&(i=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),o.axis=i&&i[1]?i[1]:"se")}),u.autoHide&&(this._handles.hide(),e(this.element).addClass("ui-resizable-autohide").mouseenter(function(){if(u.disabled)return;e(this).removeClass("ui-resizable-autohide"),o._handles.show()}).mouseleave(function(){if(u.disabled)return;o.resizing||(e(this).addClass("ui-resizable-autohide"),o._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var t,n=function(t){e(t).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(n(this.element),t=this.element,this.originalElement.css({position:t.css("position"),width:t.outerWidth(),height:t.outerHeight(),top:t.css("top"),left:t.css("left")}).insertAfter(t),t.remove()),this.originalElement.css("resize",this.originalResizeStyle),n(this.originalElement),this},_mouseCapture:function(t){var n,r,i=!1;for(n in this.handles){r=e(this.handles[n])[0];if(r===t.target||e.contains(r,t.target))i=!0}return!this.options.disabled&&i},_mouseStart:function(t){var r,i,s,o=this.options,u=this.element.position(),a=this.element;return this.resizing=!0,/absolute/.test(a.css("position"))?a.css({position:"absolute",top:a.css("top"),left:a.css("left")}):a.is(".ui-draggable")&&a.css({position:"absolute",top:u.top,left:u.left}),this._renderProxy(),r=n(this.helper.css("left")),i=n(this.helper.css("top")),o.containment&&(r+=e(o.containment).scrollLeft()||0,i+=e(o.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:r,top:i},this.size=this._helper?{width:a.outerWidth(),height:a.outerHeight()}:{width:a.width(),height:a.height()},this.originalSize=this._helper?{width:a.outerWidth(),height:a.outerHeight()}:{width:a.width(),height:a.height()},this.originalPosition={left:r,top:i},this.sizeDiff={width:a.outerWidth()-a.width(),height:a.outerHeight()-a.height()},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio=typeof o.aspectRatio=="number"?o.aspectRatio:this.originalSize.width/this.originalSize.height||1,s=e(".ui-resizable-"+this.axis).css("cursor"),e("body").css("cursor",s==="auto"?this.axis+"-resize":s),a.addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(t){var n,r=this.helper,i={},s=this.originalMousePosition,o=this.axis,u=this.position.top,a=this.position.left,f=this.size.width,l=this.size.height,c=t.pageX-s.left||0,h=t.pageY-s.top||0,p=this._change[o];if(!p)return!1;n=p.apply(this,[t,c,h]),this._updateVirtualBoundaries(t.shiftKey);if(this._aspectRatio||t.shiftKey)n=this._updateRatio(n,t);return n=this._respectSize(n,t),this._updateCache(n),this._propagate("resize",t),this.position.top!==u&&(i.top=this.position.top+"px"),this.position.left!==a&&(i.left=this.position.left+"px"),this.size.width!==f&&(i.width=this.size.width+"px"),this.size.height!==l&&(i.height=this.size.height+"px"),r.css(i),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),e.isEmptyObject(i)||this._trigger("resize",t,this.ui()),!1},_mouseStop:function(t){this.resizing=!1;var n,r,i,s,o,u,a,f=this.options,l=this;return this._helper&&(n=this._proportionallyResizeElements,r=n.length&&/textarea/i.test(n[0].nodeName),i=r&&e.ui.hasScroll(n[0],"left")?0:l.sizeDiff.height,s=r?0:l.sizeDiff.width,o={width:l.helper.width()-s,height:l.helper.height()-i},u=parseInt(l.element.css("left"),10)+(l.position.left-l.originalPosition.left)||null,a=parseInt(l.element.css("top"),10)+(l.position.top-l.originalPosition.top)||null,f.animate||this.element.css(e.extend(o,{top:a,left:u})),l.helper.height(l.size.height),l.helper.width(l.size.width),this._helper&&!f.animate&&this._proportionallyResize()),e("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",t),this._helper&&this.helper.remove(),!1},_updateVirtualBoundaries:function(e){var t,n,i,s,o,u=this.options;o={minWidth:r(u.minWidth)?u.minWidth:0,maxWidth:r(u.maxWidth)?u.maxWidth:Infinity,minHeight:r(u.minHeight)?u.minHeight:0,maxHeight:r(u.maxHeight)?u.maxHeight:Infinity};if(this._aspectRatio||e)t=o.minHeight*this.aspectRatio,i=o.minWidth/this.aspectRatio,n=o.maxHeight*this.aspectRatio,s=o.maxWidth/this.aspectRatio,t>o.minWidth&&(o.minWidth=t),i>o.minHeight&&(o.minHeight=i),ne.width,u=r(e.height)&&t.minHeight&&t.minHeight>e.height,a=this.originalPosition.left+this.originalSize.width,f=this.position.top+this.size.height,l=/sw|nw|w/.test(n),c=/nw|ne|n/.test(n);return o&&(e.width=t.minWidth),u&&(e.height=t.minHeight),i&&(e.width=t.maxWidth),s&&(e.height=t.maxHeight),o&&l&&(e.left=a-t.minWidth),i&&l&&(e.left=a-t.maxWidth),u&&c&&(e.top=f-t.minHeight),s&&c&&(e.top=f-t.maxHeight),!e.width&&!e.height&&!e.left&&e.top?e.top=null:!e.width&&!e.height&&!e.top&&e.left&&(e.left=null),e},_proportionallyResize:function(){if(!this._proportionallyResizeElements.length)return;var e,t,n,r,i,s=this.helper||this.element;for(e=0;e"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++n.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(e,t){return{width:this.originalSize.width+t}},w:function(e,t){var n=this.originalSize,r=this.originalPosition;return{left:r.left+t,width:n.width-t}},n:function(e,t,n){var r=this.originalSize,i=this.originalPosition;return{top:i.top+n,height:r.height-n}},s:function(e,t,n){return{height:this.originalSize.height+n}},se:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},sw:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,n,r]))},ne:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},nw:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,n,r]))}},_propagate:function(t,n){e.ui.plugin.call(this,t,[n,this.ui()]),t!=="resize"&&this._trigger(t,n,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),e.ui.plugin.add("resizable","animate",{stop:function(t){var n=e(this).data("ui-resizable"),r=n.options,i=n._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),o=s&&e.ui.hasScroll(i[0],"left")?0:n.sizeDiff.height,u=s?0:n.sizeDiff.width,a={width:n.size.width-u,height:n.size.height-o},f=parseInt(n.element.css("left"),10)+(n.position.left-n.originalPosition.left)||null,l=parseInt(n.element.css("top"),10)+(n.position.top-n.originalPosition.top)||null;n.element.animate(e.extend(a,l&&f?{top:l,left:f}:{}),{duration:r.animateDuration,easing:r.animateEasing,step:function(){var r={width:parseInt(n.element.css("width"),10),height:parseInt(n.element.css("height"),10),top:parseInt(n.element.css("top"),10),left:parseInt(n.element.css("left"),10)};i&&i.length&&e(i[0]).css({width:r.width,height:r.height}),n._updateCache(r),n._propagate("resize",t)}})}}),e.ui.plugin.add("resizable","containment",{start:function(){var t,r,i,s,o,u,a,f=e(this).data("ui-resizable"),l=f.options,c=f.element,h=l.containment,p=h instanceof e?h.get(0):/parent/.test(h)?c.parent().get(0):h;if(!p)return;f.containerElement=e(p),/document/.test(h)||h===document?(f.containerOffset={left:0,top:0},f.containerPosition={left:0,top:0},f.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight}):(t=e(p),r=[],e(["Top","Right","Left","Bottom"]).each(function(e,i){r[e]=n(t.css("padding"+i))}),f.containerOffset=t.offset(),f.containerPosition=t.position(),f.containerSize={height:t.innerHeight()-r[3],width:t.innerWidth()-r[1]},i=f.containerOffset,s=f.containerSize.height,o=f.containerSize.width,u=e.ui.hasScroll(p,"left")?p.scrollWidth:o,a=e.ui.hasScroll(p)?p.scrollHeight:s,f.parentData={element:p,left:i.left,top:i.top,width:u,height:a})},resize:function(t){var n,r,i,s,o=e(this).data("ui-resizable"),u=o.options,a=o.containerOffset,f=o.position,l=o._aspectRatio||t.shiftKey,c={top:0,left:0},h=o.containerElement;h[0]!==document&&/static/.test(h.css("position"))&&(c=a),f.left<(o._helper?a.left:0)&&(o.size.width=o.size.width+(o._helper?o.position.left-a.left:o.position.left-c.left),l&&(o.size.height=o.size.width/o.aspectRatio),o.position.left=u.helper?a.left:0),f.top<(o._helper?a.top:0)&&(o.size.height=o.size.height+(o._helper?o.position.top-a.top:o.position.top),l&&(o.size.width=o.size.height*o.aspectRatio),o.position.top=o._helper?a.top:0),o.offset.left=o.parentData.left+o.position.left,o.offset.top=o.parentData.top+o.position.top,n=Math.abs((o._helper?o.offset.left-c.left:o.offset.left-c.left)+o.sizeDiff.width),r=Math.abs((o._helper?o.offset.top-c.top:o.offset.top-a.top)+o.sizeDiff.height),i=o.containerElement.get(0)===o.element.parent().get(0),s=/relative|absolute/.test(o.containerElement.css("position")),i&&s&&(n-=o.parentData.left),n+o.size.width>=o.parentData.width&&(o.size.width=o.parentData.width-n,l&&(o.size.height=o.size.width/o.aspectRatio)),r+o.size.height>=o.parentData.height&&(o.size.height=o.parentData.height-r,l&&(o.size.width=o.size.height*o.aspectRatio))},stop:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.containerOffset,i=t.containerPosition,s=t.containerElement,o=e(t.helper),u=o.offset(),a=o.outerWidth()-t.sizeDiff.width,f=o.outerHeight()-t.sizeDiff.height;t._helper&&!n.animate&&/relative/.test(s.css("position"))&&e(this).css({left:u.left-i.left-r.left,width:a,height:f}),t._helper&&!n.animate&&/static/.test(s.css("position"))&&e(this).css({left:u.left-i.left-r.left,width:a,height:f})}}),e.ui.plugin.add("resizable","alsoResize",{start:function(){var t=e(this).data("ui-resizable"),n=t.options,r=function(t){e(t).each(function(){var t=e(this);t.data("ui-resizable-alsoresize",{width:parseInt(t.width(),10),height:parseInt(t.height(),10),left:parseInt(t.css("left"),10),top:parseInt(t.css("top"),10)})})};typeof n.alsoResize=="object"&&!n.alsoResize.parentNode?n.alsoResize.length?(n.alsoResize=n.alsoResize[0],r(n.alsoResize)):e.each(n.alsoResize,function(e){r(e)}):r(n.alsoResize)},resize:function(t,n){var r=e(this).data("ui-resizable"),i=r.options,s=r.originalSize,o=r.originalPosition,u={height:r.size.height-s.height||0,width:r.size.width-s.width||0,top:r.position.top-o.top||0,left:r.position.left-o.left||0},a=function(t,r){e(t).each(function(){var t=e(this),i=e(this).data("ui-resizable-alsoresize"),s={},o=r&&r.length?r:t.parents(n.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(o,function(e,t){var n=(i[t]||0)+(u[t]||0);n&&n>=0&&(s[t]=n||null)}),t.css(s)})};typeof i.alsoResize=="object"&&!i.alsoResize.nodeType?e.each(i.alsoResize,function(e,t){a(e,t)}):a(i.alsoResize)},stop:function(){e(this).removeData("resizable-alsoresize")}}),e.ui.plugin.add("resizable","ghost",{start:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.size;t.ghost=t.originalElement.clone(),t.ghost.css({opacity:.25,display:"block",position:"relative",height:r.height,width:r.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof n.ghost=="string"?n.ghost:""),t.ghost.appendTo(t.helper)},resize:function(){var t=e(this).data("ui-resizable");t.ghost&&t.ghost.css({position:"relative",height:t.size.height,width:t.size.width})},stop:function(){var t=e(this).data("ui-resizable");t.ghost&&t.helper&&t.helper.get(0).removeChild(t.ghost.get(0))}}),e.ui.plugin.add("resizable","grid",{resize:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.size,i=t.originalSize,s=t.originalPosition,o=t.axis,u=typeof n.grid=="number"?[n.grid,n.grid]:n.grid,a=u[0]||1,f=u[1]||1,l=Math.round((r.width-i.width)/a)*a,c=Math.round((r.height-i.height)/f)*f,h=i.width+l,p=i.height+c,d=n.maxWidth&&n.maxWidthh,g=n.minHeight&&n.minHeight>p;n.grid=u,m&&(h+=a),g&&(p+=f),d&&(h-=a),v&&(p-=f),/^(se|s|e)$/.test(o)?(t.size.width=h,t.size.height=p):/^(ne)$/.test(o)?(t.size.width=h,t.size.height=p,t.position.top=s.top-c):/^(sw)$/.test(o)?(t.size.width=h,t.size.height=p,t.position.left=s.left-l):(t.size.width=h,t.size.height=p,t.position.top=s.top-c,t.position.left=s.left-l)}})}(jQuery),function(e,t){e.widget("ui.selectable",e.ui.mouse,{version:"1.10.1",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var t,n=this;this.element.addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){t=e(n.options.filter,n.element[0]),t.addClass("ui-selectee"),t.each(function(){var t=e(this),n=t.offset();e.data(this,"selectable-item",{element:this,$element:t,left:n.left,top:n.top,right:n.left+t.outerWidth(),bottom:n.top+t.outerHeight(),startselected:!1,selected:t.hasClass("ui-selected"),selecting:t.hasClass("ui-selecting"),unselecting:t.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=t.addClass("ui-selectee"),this._mouseInit(),this.helper=e("
")},_destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled"),this._mouseDestroy()},_mouseStart:function(t){var n=this,r=this.options;this.opos=[t.pageX,t.pageY];if(this.options.disabled)return;this.selectees=e(r.filter,this.element[0]),this._trigger("start",t),e(r.appendTo).append(this.helper),this.helper.css({left:t.pageX,top:t.pageY,width:0,height:0}),r.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var r=e.data(this,"selectable-item");r.startselected=!0,!t.metaKey&&!t.ctrlKey&&(r.$element.removeClass("ui-selected"),r.selected=!1,r.$element.addClass("ui-unselecting"),r.unselecting=!0,n._trigger("unselecting",t,{unselecting:r.element}))}),e(t.target).parents().addBack().each(function(){var r,i=e.data(this,"selectable-item");if(i)return r=!t.metaKey&&!t.ctrlKey||!i.$element.hasClass("ui-selected"),i.$element.removeClass(r?"ui-unselecting":"ui-selected").addClass(r?"ui-selecting":"ui-unselecting"),i.unselecting=!r,i.selecting=r,i.selected=r,r?n._trigger("selecting",t,{selecting:i.element}):n._trigger("unselecting",t,{unselecting:i.element}),!1})},_mouseDrag:function(t){this.dragged=!0;if(this.options.disabled)return;var n,r=this,i=this.options,s=this.opos[0],o=this.opos[1],u=t.pageX,a=t.pageY;return s>u&&(n=u,u=s,s=n),o>a&&(n=a,a=o,o=n),this.helper.css({left:s,top:o,width:u-s,height:a-o}),this.selectees.each(function(){var n=e.data(this,"selectable-item"),f=!1;if(!n||n.element===r.element[0])return;i.tolerance==="touch"?f=!(n.left>u||n.righta||n.bottoms&&n.righto&&n.bottomt&&e *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_create:function(){var e=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?e.axis==="x"||/left|right/.test(this.items[0].item.css("float"))||/inline|table-cell/.test(this.items[0].item.css("display")):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var e=this.items.length-1;e>=0;e--)this.items[e].item.removeData(this.widgetName+"-item");return this},_setOption:function(t,n){t==="disabled"?(this.options[t]=n,this.widget().toggleClass("ui-sortable-disabled",!!n)):e.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(t,n){var r=null,i=!1,s=this;if(this.reverting)return!1;if(this.options.disabled||this.options.type==="static")return!1;this._refreshItems(t),e(t.target).parents().each(function(){if(e.data(this,s.widgetName+"-item")===s)return r=e(this),!1}),e.data(t.target,s.widgetName+"-item")===s&&(r=e(t.target));if(!r)return!1;if(this.options.handle&&!n){e(this.options.handle,r).find("*").addBack().each(function(){this===t.target&&(i=!0)});if(!i)return!1}return this.currentItem=r,this._removeCurrentsFromItems(),!0},_mouseStart:function(t,n,r){var i,s=this.options;this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(t),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,s.cursorAt&&this._adjustOffsetFromHelper(s.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),s.containment&&this._setContainment(),s.cursor&&(e("body").css("cursor")&&(this._storedCursor=e("body").css("cursor")),e("body").css("cursor",s.cursor)),s.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",s.opacity)),s.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",s.zIndex)),this.scrollParent[0]!==document&&this.scrollParent[0].tagName!=="HTML"&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",t,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions();if(!r)for(i=this.containers.length-1;i>=0;i--)this.containers[i]._trigger("activate",t,this._uiHash(this));return e.ui.ddmanager&&(e.ui.ddmanager.current=this),e.ui.ddmanager&&!s.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(t),!0},_mouseDrag:function(t){var n,r,i,s,o=this.options,u=!1;this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==document&&this.scrollParent[0].tagName!=="HTML"?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY=0;n--){r=this.items[n],i=r.item[0],s=this._intersectsWithPointer(r);if(!s)continue;if(r.instance!==this.currentContainer)continue;if(i!==this.currentItem[0]&&this.placeholder[s===1?"next":"prev"]()[0]!==i&&!e.contains(this.placeholder[0],i)&&(this.options.type==="semi-dynamic"?!e.contains(this.element[0],i):!0)){this.direction=s===1?"down":"up";if(this.options.tolerance!=="pointer"&&!this._intersectsWithSides(r))break;this._rearrange(t,r),this._trigger("change",t,this._uiHash());break}}return this._contactContainers(t),e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),this._trigger("sort",t,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(t,n){if(!t)return;e.ui.ddmanager&&!this.options.dropBehaviour&&e.ui.ddmanager.drop(this,t);if(this.options.revert){var r=this,i=this.placeholder.offset();this.reverting=!0,e(this.helper).animate({left:i.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollLeft),top:i.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){r._clear(t)})}else this._clear(t,n);return!1},cancel:function(){if(this.dragging){this._mouseUp({target:null}),this.options.helper==="original"?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var t=this.containers.length-1;t>=0;t--)this.containers[t]._trigger("deactivate",null,this._uiHash(this)),this.containers[t].containerCache.over&&(this.containers[t]._trigger("out",null,this._uiHash(this)),this.containers[t].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.options.helper!=="original"&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),e.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?e(this.domPosition.prev).after(this.currentItem):e(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(t){var n=this._getItemsAsjQuery(t&&t.connected),r=[];return t=t||{},e(n).each(function(){var n=(e(t.item||this).attr(t.attribute||"id")||"").match(t.expression||/(.+)[\-=_](.+)/);n&&r.push((t.key||n[1]+"[]")+"="+(t.key&&t.expression?n[1]:n[2]))}),!r.length&&t.key&&r.push(t.key+"="),r.join("&")},toArray:function(t){var n=this._getItemsAsjQuery(t&&t.connected),r=[];return t=t||{},n.each(function(){r.push(e(t.item||this).attr(t.attribute||"id")||"")}),r},_intersectsWith:function(e){var t=this.positionAbs.left,n=t+this.helperProportions.width,r=this.positionAbs.top,i=r+this.helperProportions.height,s=e.left,o=s+e.width,u=e.top,a=u+e.height,f=this.offset.click.top,l=this.offset.click.left,c=r+f>u&&r+fs&&t+le[this.floating?"width":"height"]?c:s0?"down":"up")},_getDragHorizontalDirection:function(){var e=this.positionAbs.left-this.lastPositionAbs.left;return e!==0&&(e>0?"right":"left")},refresh:function(e){return this._refreshItems(e),this.refreshPositions(),this},_connectWith:function(){var e=this.options;return e.connectWith.constructor===String?[e.connectWith]:e.connectWith},_getItemsAsjQuery:function(t){var n,r,i,s,o=[],u=[],a=this._connectWith();if(a&&t)for(n=a.length-1;n>=0;n--){i=e(a[n]);for(r=i.length-1;r>=0;r--)s=e.data(i[r],this.widgetFullName),s&&s!==this&&!s.options.disabled&&u.push([e.isFunction(s.options.items)?s.options.items.call(s.element):e(s.options.items,s.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),s])}u.push([e.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):e(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(n=u.length-1;n>=0;n--)u[n][0].each(function(){o.push(this)});return e(o)},_removeCurrentsFromItems:function(){var t=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=e.grep(this.items,function(e){for(var n=0;n=0;n--){i=e(h[n]);for(r=i.length-1;r>=0;r--)s=e.data(i[r],this.widgetFullName),s&&s!==this&&!s.options.disabled&&(c.push([e.isFunction(s.options.items)?s.options.items.call(s.element[0],t,{item:this.currentItem}):e(s.options.items,s.element),s]),this.containers.push(s))}for(n=c.length-1;n>=0;n--){o=c[n][1],u=c[n][0];for(r=0,f=u.length;r=0;n--){r=this.items[n];if(r.instance!==this.currentContainer&&this.currentContainer&&r.item[0]!==this.currentItem[0])continue;i=this.options.toleranceElement?e(this.options.toleranceElement,r.item):r.item,t||(r.width=i.outerWidth(),r.height=i.outerHeight()),s=i.offset(),r.left=s.left,r.top=s.top}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(n=this.containers.length-1;n>=0;n--)s=this.containers[n].element.offset(),this.containers[n].containerCache.left=s.left,this.containers[n].containerCache.top=s.top,this.containers[n].containerCache.width=this.containers[n].element.outerWidth(),this.containers[n].containerCache.height=this.containers[n].element.outerHeight();return this},_createPlaceholder:function(t){t=t||this;var n,r=t.options;if(!r.placeholder||r.placeholder.constructor===String)n=r.placeholder,r.placeholder={element:function(){var r=e(document.createElement(t.currentItem[0].nodeName)).addClass(n||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];return n||(r.style.visibility="hidden"),r},update:function(e,i){if(n&&!r.forcePlaceholderSize)return;i.height()||i.height(t.currentItem.innerHeight()-parseInt(t.currentItem.css("paddingTop")||0,10)-parseInt(t.currentItem.css("paddingBottom")||0,10)),i.width()||i.width(t.currentItem.innerWidth()-parseInt(t.currentItem.css("paddingLeft")||0,10)-parseInt(t.currentItem.css("paddingRight")||0,10))}};t.placeholder=e(r.placeholder.element.call(t.element,t.currentItem)),t.currentItem.after(t.placeholder),r.placeholder.update(t,t.placeholder)},_contactContainers:function(t){var n,r,i,s,o,u,a,f,l,c=null,h=null;for(n=this.containers.length-1;n>=0;n--){if(e.contains(this.currentItem[0],this.containers[n].element[0]))continue;if(this._intersectsWith(this.containers[n].containerCache)){if(c&&e.contains(this.containers[n].element[0],c.element[0]))continue;c=this.containers[n],h=n}else this.containers[n].containerCache.over&&(this.containers[n]._trigger("out",t,this._uiHash(this)),this.containers[n].containerCache.over=0)}if(!c)return;if(this.containers.length===1)this.containers[h]._trigger("over",t,this._uiHash(this)),this.containers[h].containerCache.over=1;else{i=1e4,s=null,o=this.containers[h].floating?"left":"top",u=this.containers[h].floating?"width":"height",a=this.positionAbs[o]+this.offset.click[o];for(r=this.items.length-1;r>=0;r--){if(!e.contains(this.containers[h].element[0],this.items[r].item[0]))continue;if(this.items[r].item[0]===this.currentItem[0])continue;f=this.items[r].item.offset()[o],l=!1,Math.abs(f-a)>Math.abs(f+this.items[r][u]-a)&&(l=!0,f+=this.items[r][u]),Math.abs(f-a)this.containment[2]&&(s=this.containment[2]+this.offset.click.left),t.pageY-this.offset.click.top>this.containment[3]&&(o=this.containment[3]+this.offset.click.top)),i.grid&&(n=this.originalPageY+Math.round((o-this.originalPageY)/i.grid[1])*i.grid[1],o=this.containment?n-this.offset.click.top>=this.containment[1]&&n-this.offset.click.top<=this.containment[3]?n:n-this.offset.click.top>=this.containment[1]?n-i.grid[1]:n+i.grid[1]:n,r=this.originalPageX+Math.round((s-this.originalPageX)/i.grid[0])*i.grid[0],s=this.containment?r-this.offset.click.left>=this.containment[0]&&r-this.offset.click.left<=this.containment[2]?r:r-this.offset.click.left>=this.containment[0]?r-i.grid[0]:r+i.grid[0]:r)),{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition==="fixed"?-this.scrollParent.scrollTop():a?0:u.scrollTop()),left:s-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():a?0:u.scrollLeft())}},_rearrange:function(e,t,n,r){n?n[0].appendChild(this.placeholder[0]):t.item[0].parentNode.insertBefore(this.placeholder[0],this.direction==="down"?t.item[0]:t.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var i=this.counter;this._delay(function(){i===this.counter&&this.refreshPositions(!r)})},_clear:function(t,n){this.reverting=!1;var r,i=[];!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null;if(this.helper[0]===this.currentItem[0]){for(r in this._storedCSS)if(this._storedCSS[r]==="auto"||this._storedCSS[r]==="static")this._storedCSS[r]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!n&&i.push(function(e){this._trigger("receive",e,this._uiHash(this.fromOutside))}),(this.fromOutside||this.domPosition.prev!==this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!==this.currentItem.parent()[0])&&!n&&i.push(function(e){this._trigger("update",e,this._uiHash())}),this!==this.currentContainer&&(n||(i.push(function(e){this._trigger("remove",e,this._uiHash())}),i.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),i.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer))));for(r=this.containers.length-1;r>=0;r--)n||i.push(function(e){return function(t){e._trigger("deactivate",t,this._uiHash(this))}}.call(this,this.containers[r])),this.containers[r].containerCache.over&&(i.push(function(e){return function(t){e._trigger("out",t,this._uiHash(this))}}.call(this,this.containers[r])),this.containers[r].containerCache.over=0);this._storedCursor&&e("body").css("cursor",this._storedCursor),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex",this._storedZIndex==="auto"?"":this._storedZIndex),this.dragging=!1;if(this.cancelHelperRemoval){if(!n){this._trigger("beforeStop",t,this._uiHash());for(r=0;re?0:r.max")[0],l,c=e.each;f.style.cssText="background-color:rgba(1,1,1,.5)",a.rgba=f.style.backgroundColor.indexOf("rgba")>-1,c(o,function(e,t){t.cache="_"+e,t.props.alpha={idx:3,type:"percent",def:1}}),s.fn=e.extend(s.prototype,{parse:function(n,r,i,u){if(n===t)return this._rgba=[null,null,null,null],this;if(n.jquery||n.nodeType)n=e(n).css(r),r=t;var a=this,f=e.type(n),d=this._rgba=[];r!==t&&(n=[n,r,i,u],f="array");if(f==="string")return this.parse(p(n)||l._default);if(f==="array")return c(o.rgba.props,function(e,t){d[t.idx]=h(n[t.idx],t)}),this;if(f==="object")return n instanceof s?c(o,function(e,t){n[t.cache]&&(a[t.cache]=n[t.cache].slice())}):c(o,function(t,r){var i=r.cache;c(r.props,function(e,t){if(!a[i]&&r.to){if(e==="alpha"||n[e]==null)return;a[i]=r.to(a._rgba)}a[i][t.idx]=h(n[e],t,!0)}),a[i]&&e.inArray(null,a[i].slice(0,3))<0&&(a[i][3]=1,r.from&&(a._rgba=r.from(a[i])))}),this},is:function(e){var t=s(e),n=!0,r=this;return c(o,function(e,i){var s,o=t[i.cache];return o&&(s=r[i.cache]||i.to&&i.to(r._rgba)||[],c(i.props,function(e,t){if(o[t.idx]!=null)return n=o[t.idx]===s[t.idx],n})),n}),n},_space:function(){var e=[],t=this;return c(o,function(n,r){t[r.cache]&&e.push(n)}),e.pop()},transition:function(e,t){var n=s(e),r=n._space(),i=o[r],a=this.alpha()===0?s("transparent"):this,f=a[i.cache]||i.to(a._rgba),l=f.slice();return n=n[i.cache],c(i.props,function(e,r){var i=r.idx,s=f[i],o=n[i],a=u[r.type]||{};if(o===null)return;s===null?l[i]=o:(a.mod&&(o-s>a.mod/2?s+=a.mod:s-o>a.mod/2&&(s-=a.mod)),l[i]=h((o-s)*t+s,r))}),this[r](l)},blend:function(t){if(this._rgba[3]===1)return this;var n=this._rgba.slice(),r=n.pop(),i=s(t)._rgba;return s(e.map(n,function(e,t){return(1-r)*i[t]+r*e}))},toRgbaString:function(){var t="rgba(",n=e.map(this._rgba,function(e,t){return e==null?t>2?1:0:e});return n[3]===1&&(n.pop(),t="rgb("),t+n.join()+")"},toHslaString:function(){var t="hsla(",n=e.map(this.hsla(),function(e,t){return e==null&&(e=t>2?1:0),t&&t<3&&(e=Math.round(e*100)+"%"),e});return n[3]===1&&(n.pop(),t="hsl("),t+n.join()+")"},toHexString:function(t){var n=this._rgba.slice(),r=n.pop();return t&&n.push(~~(r*255)),"#"+e.map(n,function(e){return e=(e||0).toString(16),e.length===1?"0"+e:e}).join("")},toString:function(){return this._rgba[3]===0?"transparent":this.toRgbaString()}}),s.fn.parse.prototype=s.fn,o.hsla.to=function(e){if(e[0]==null||e[1]==null||e[2]==null)return[null,null,null,e[3]];var t=e[0]/255,n=e[1]/255,r=e[2]/255,i=e[3],s=Math.max(t,n,r),o=Math.min(t,n,r),u=s-o,a=s+o,f=a*.5,l,c;return o===s?l=0:t===s?l=60*(n-r)/u+360:n===s?l=60*(r-t)/u+120:l=60*(t-n)/u+240,u===0?c=0:f<=.5?c=u/a:c=u/(2-a),[Math.round(l)%360,c,f,i==null?1:i]},o.hsla.from=function(e){if(e[0]==null||e[1]==null||e[2]==null)return[null,null,null,e[3]];var t=e[0]/360,n=e[1],r=e[2],i=e[3],s=r<=.5?r*(1+n):r+n-r*n,o=2*r-s;return[Math.round(d(o,s,t+1/3)*255),Math.round(d(o,s,t)*255),Math.round(d(o,s,t-1/3)*255),i]},c(o,function(n,i){var o=i.props,u=i.cache,a=i.to,f=i.from;s.fn[n]=function(n){a&&!this[u]&&(this[u]=a(this._rgba));if(n===t)return this[u].slice();var r,i=e.type(n),l=i==="array"||i==="object"?n:arguments,p=this[u].slice();return c(o,function(e,t){var n=l[i==="object"?e:t.idx];n==null&&(n=p[t.idx]),p[t.idx]=h(n,t)}),f?(r=s(f(p)),r[u]=p,r):s(p)},c(o,function(t,i){if(s.fn[t])return;s.fn[t]=function(s){var o=e.type(s),u=t==="alpha"?this._hsla?"hsla":"rgba":n,a=this[u](),f=a[i.idx],l;return o==="undefined"?f:(o==="function"&&(s=s.call(this,f),o=e.type(s)),s==null&&i.empty?this:(o==="string"&&(l=r.exec(s),l&&(s=f+parseFloat(l[2])*(l[1]==="+"?1:-1))),a[i.idx]=s,this[u](a)))}})}),s.hook=function(t){var n=t.split(" ");c(n,function(t,n){e.cssHooks[n]={set:function(t,r){var i,o,u="";if(r!=="transparent"&&(e.type(r)!=="string"||(i=p(r)))){r=s(i||r);if(!a.rgba&&r._rgba[3]!==1){o=n==="backgroundColor"?t.parentNode:t;while((u===""||u==="transparent")&&o&&o.style)try{u=e.css(o,"backgroundColor"),o=o.parentNode}catch(f){}r=r.blend(u&&u!=="transparent"?u:"_default")}r=r.toRgbaString()}try{t.style[n]=r}catch(f){}}},e.fx.step[n]=function(t){t.colorInit||(t.start=s(t.elem,n),t.end=s(t.end),t.colorInit=!0),e.cssHooks[n].set(t.elem,t.start.transition(t.end,t.pos))}})},s.hook(n),e.cssHooks.borderColor={expand:function(e){var t={};return c(["Top","Right","Bottom","Left"],function(n,r){t["border"+r+"Color"]=e}),t}},l=e.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}}(jQuery),function(){function i(t){var n,r,i=t.ownerDocument.defaultView?t.ownerDocument.defaultView.getComputedStyle(t,null):t.currentStyle,s={};if(i&&i.length&&i[0]&&i[i[0]]){r=i.length;while(r--)n=i[r],typeof i[n]=="string"&&(s[e.camelCase(n)]=i[n])}else for(n in i)typeof i[n]=="string"&&(s[n]=i[n]);return s}function s(t,n){var i={},s,o;for(s in n)o=n[s],t[s]!==o&&!r[s]&&(e.fx.step[s]||!isNaN(parseFloat(o)))&&(i[s]=o);return i}var n=["add","remove","toggle"],r={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};e.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(t,n){e.fx.step[n]=function(e){if(e.end!=="none"&&!e.setAttr||e.pos===1&&!e.setAttr)jQuery.style(e.elem,n,e.end),e.setAttr=!0}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}),e.effects.animateClass=function(t,r,o,u){var a=e.speed(r,o,u);return this.queue(function(){var r=e(this),o=r.attr("class")||"",u,f=a.children?r.find("*").addBack():r;f=f.map(function(){var t=e(this);return{el:t,start:i(this)}}),u=function(){e.each(n,function(e,n){t[n]&&r[n+"Class"](t[n])})},u(),f=f.map(function(){return this.end=i(this.el[0]),this.diff=s(this.start,this.end),this}),r.attr("class",o),f=f.map(function(){var t=this,n=e.Deferred(),r=e.extend({},a,{queue:!1,complete:function(){n.resolve(t)}});return this.el.animate(this.diff,r),n.promise()}),e.when.apply(e,f.get()).done(function(){u(),e.each(arguments,function(){var t=this.el;e.each(this.diff,function(e){t.css(e,"")})}),a.complete.call(r[0])})})},e.fn.extend({_addClass:e.fn.addClass,addClass:function(t,n,r,i){return n?e.effects.animateClass.call(this,{add:t},n,r,i):this._addClass(t)},_removeClass:e.fn.removeClass,removeClass:function(t,n,r,i){return arguments.length>1?e.effects.animateClass.call(this,{remove:t},n,r,i):this._removeClass.apply(this,arguments)},_toggleClass:e.fn.toggleClass,toggleClass:function(n,r,i,s,o){return typeof r=="boolean"||r===t?i?e.effects.animateClass.call(this,r?{add:n}:{remove:n},i,s,o):this._toggleClass(n,r):e.effects.animateClass.call(this,{toggle:n},r,i,s)},switchClass:function(t,n,r,i,s){return e.effects.animateClass.call(this,{add:n,remove:t},r,i,s)}})}(),function(){function r(t,n,r,i){e.isPlainObject(t)&&(n=t,t=t.effect),t={effect:t},n==null&&(n={}),e.isFunction(n)&&(i=n,r=null,n={});if(typeof n=="number"||e.fx.speeds[n])i=r,r=n,n={};return e.isFunction(r)&&(i=r,r=null),n&&e.extend(t,n),r=r||n.duration,t.duration=e.fx.off?0:typeof r=="number"?r:r in e.fx.speeds?e.fx.speeds[r]:e.fx.speeds._default,t.complete=i||n.complete,t}function i(t){return!t||typeof t=="number"||e.fx.speeds[t]?!0:typeof t=="string"&&!e.effects.effect[t]}e.extend(e.effects,{version:"1.10.1",save:function(e,t){for(var r=0;r").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),i={width:t.width(),height:t.height()},s=document.activeElement;try{s.id}catch(o){s=document.body}return t.wrap(r),(t[0]===s||e.contains(t[0],s))&&e(s).focus(),r=t.parent(),t.css("position")==="static"?(r.css({position:"relative"}),t.css({position:"relative"})):(e.extend(n,{position:t.css("position"),zIndex:t.css("z-index")}),e.each(["top","left","bottom","right"],function(e,r){n[r]=t.css(r),isNaN(parseInt(n[r],10))&&(n[r]="auto")}),t.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),t.css(i),r.css(n).show()},removeWrapper:function(t){var n=document.activeElement;return t.parent().is(".ui-effects-wrapper")&&(t.parent().replaceWith(t),(t[0]===n||e.contains(t[0],n))&&e(n).focus()),t},setTransition:function(t,n,r,i){return i=i||{},e.each(n,function(e,n){var s=t.cssUnit(n);s[0]>0&&(i[n]=s[0]*r+s[1])}),i}}),e.fn.extend({effect:function(){function o(n){function u(){e.isFunction(i)&&i.call(r[0]),e.isFunction(n)&&n()}var r=e(this),i=t.complete,o=t.mode;(r.is(":hidden")?o==="hide":o==="show")?u():s.call(r[0],t,u)}var t=r.apply(this,arguments),n=t.mode,i=t.queue,s=e.effects.effect[t.effect];return e.fx.off||!s?n?this[n](t.duration,t.complete):this.each(function(){t.complete&&t.complete.call(this)}):i===!1?this.each(o):this.queue(i||"fx",o)},_show:e.fn.show,show:function(e){if(i(e))return this._show.apply(this,arguments);var t=r.apply(this,arguments);return t.mode="show",this.effect.call(this,t)},_hide:e.fn.hide,hide:function(e){if(i(e))return this._hide.apply(this,arguments);var t=r.apply(this,arguments);return t.mode="hide",this.effect.call(this,t)},__toggle:e.fn.toggle,toggle:function(t){if(i(t)||typeof t=="boolean"||e.isFunction(t))return this.__toggle.apply(this,arguments);var n=r.apply(this,arguments);return n.mode="toggle",this.effect.call(this,n)},cssUnit:function(t){var n=this.css(t),r=[];return e.each(["em","px","%","pt"],function(e,t){n.indexOf(t)>0&&(r=[parseFloat(n),t])}),r}})}(),function(){var t={};e.each(["Quad","Cubic","Quart","Quint","Expo"],function(e,n){t[n]=function(t){return Math.pow(t,e+2)}}),e.extend(t,{Sine:function(e){return 1-Math.cos(e*Math.PI/2)},Circ:function(e){return 1-Math.sqrt(1-e*e)},Elastic:function(e){return e===0||e===1?e:-Math.pow(2,8*(e-1))*Math.sin(((e-1)*80-7.5)*Math.PI/15)},Back:function(e){return e*e*(3*e-2)},Bounce:function(e){var t,n=4;while(e<((t=Math.pow(2,--n))-1)/11);return 1/Math.pow(4,3-n)-7.5625*Math.pow((t*3-2)/22-e,2)}}),e.each(t,function(t,n){e.easing["easeIn"+t]=n,e.easing["easeOut"+t]=function(e){return 1-n(1-e)},e.easing["easeInOut"+t]=function(e){return e<.5?n(e*2)/2:1-n(e*-2+2)/2}})}()}(jQuery),function(e,t){var n=0,r={},i={};r.height=r.paddingTop=r.paddingBottom=r.borderTopWidth=r.borderBottomWidth="hide",i.height=i.paddingTop=i.paddingBottom=i.borderTopWidth=i.borderBottomWidth="show",e.widget("ui.accordion",{version:"1.10.1",options:{active:0,animate:{},collapsible:!1,event:"click",header:"> li > :first-child,> :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},_create:function(){var t=this.options;this.prevShow=this.prevHide=e(),this.element.addClass("ui-accordion ui-widget ui-helper-reset").attr("role","tablist"),!t.collapsible&&(t.active===!1||t.active==null)&&(t.active=0),this._processPanels(),t.active<0&&(t.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():e(),content:this.active.length?this.active.next():e()}},_createIcons:function(){var t=this.options.icons;t&&(e("").addClass("ui-accordion-header-icon ui-icon "+t.header).prependTo(this.headers),this.active.children(".ui-accordion-header-icon").removeClass(t.header).addClass(t.activeHeader),this.headers.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.removeClass("ui-accordion-icons").children(".ui-accordion-header-icon").remove()},_destroy:function(){var e;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),this.headers.removeClass("ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-selected").removeAttr("aria-controls").removeAttr("tabIndex").each(function(){/^ui-accordion/.test(this.id)&&this.removeAttribute("id")}),this._destroyIcons(),e=this.headers.next().css("display","").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-labelledby").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled").each(function(){/^ui-accordion/.test(this.id)&&this.removeAttribute("id")}),this.options.heightStyle!=="content"&&e.css("height","")},_setOption:function(e,t){if(e==="active"){this._activate(t);return}e==="event"&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(t)),this._super(e,t),e==="collapsible"&&!t&&this.options.active===!1&&this._activate(0),e==="icons"&&(this._destroyIcons(),t&&this._createIcons()),e==="disabled"&&this.headers.add(this.headers.next()).toggleClass("ui-state-disabled",!!t)},_keydown:function(t){if(t.altKey||t.ctrlKey)return;var n=e.ui.keyCode,r=this.headers.length,i=this.headers.index(t.target),s=!1;switch(t.keyCode){case n.RIGHT:case n.DOWN:s=this.headers[(i+1)%r];break;case n.LEFT:case n.UP:s=this.headers[(i-1+r)%r];break;case n.SPACE:case n.ENTER:this._eventHandler(t);break;case n.HOME:s=this.headers[0];break;case n.END:s=this.headers[r-1]}s&&(e(t.target).attr("tabIndex",-1),e(s).attr("tabIndex",0),s.focus(),t.preventDefault())},_panelKeyDown:function(t){t.keyCode===e.ui.keyCode.UP&&t.ctrlKey&&e(t.currentTarget).prev().focus()},refresh:function(){var t=this.options;this._processPanels();if(t.active===!1&&t.collapsible===!0||!this.headers.length)t.active=!1,this.active=e();t.active===!1?this._activate(0):this.active.length&&!e.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(t.active=!1,this.active=e()):this._activate(Math.max(0,t.active-1)):t.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){this.headers=this.element.find(this.options.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all"),this.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom").filter(":not(.ui-accordion-content-active)").hide()},_refresh:function(){var t,r=this.options,i=r.heightStyle,s=this.element.parent(),o=this.accordionId="ui-accordion-"+(this.element.attr("id")||++n);this.active=this._findActive(r.active).addClass("ui-accordion-header-active ui-state-active ui-corner-top").removeClass("ui-corner-all"),this.active.next().addClass("ui-accordion-content-active").show(),this.headers.attr("role","tab").each(function(t){var n=e(this),r=n.attr("id"),i=n.next(),s=i.attr("id");r||(r=o+"-header-"+t,n.attr("id",r)),s||(s=o+"-panel-"+t,i.attr("id",s)),n.attr("aria-controls",s),i.attr("aria-labelledby",r)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false",tabIndex:-1}).next().attr({"aria-expanded":"false","aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true",tabIndex:0}).next().attr({"aria-expanded":"true","aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(r.event),i==="fill"?(t=s.height(),this.element.siblings(":visible").each(function(){var n=e(this),r=n.css("position");if(r==="absolute"||r==="fixed")return;t-=n.outerHeight(!0)}),this.headers.each(function(){t-=e(this).outerHeight(!0)}),this.headers.next().each(function(){e(this).height(Math.max(0,t-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):i==="auto"&&(t=0,this.headers.next().each(function(){t=Math.max(t,e(this).css("height","").height())}).height(t))},_activate:function(t){var n=this._findActive(t)[0];if(n===this.active[0])return;n=n||this.active[0],this._eventHandler({target:n,currentTarget:n,preventDefault:e.noop})},_findActive:function(t){return typeof t=="number"?this.headers.eq(t):e()},_setupEvents:function(t){var n={keydown:"_keydown"};t&&e.each(t.split(" "),function(e,t){n[t]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,n),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(t){var n=this.options,r=this.active,i=e(t.currentTarget),s=i[0]===r[0],o=s&&n.collapsible,u=o?e():i.next(),a=r.next(),f={oldHeader:r,oldPanel:a,newHeader:o?e():i,newPanel:u};t.preventDefault();if(s&&!n.collapsible||this._trigger("beforeActivate",t,f)===!1)return;n.active=o?!1:this.headers.index(i),this.active=s?e():i,this._toggle(f),r.removeClass("ui-accordion-header-active ui-state-active"),n.icons&&r.children(".ui-accordion-header-icon").removeClass(n.icons.activeHeader).addClass(n.icons.header),s||(i.removeClass("ui-corner-all").addClass("ui-accordion-header-active ui-state-active ui-corner-top"),n.icons&&i.children(".ui-accordion-header-icon").removeClass(n.icons.header).addClass(n.icons.activeHeader),i.next().addClass("ui-accordion-content-active"))},_toggle:function(t){var n=t.newPanel,r=this.prevShow.length?this.prevShow:t.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=n,this.prevHide=r,this.options.animate?this._animate(n,r,t):(r.hide(),n.show(),this._toggleComplete(t)),r.attr({"aria-expanded":"false","aria-hidden":"true"}),r.prev().attr("aria-selected","false"),n.length&&r.length?r.prev().attr("tabIndex",-1):n.length&&this.headers.filter(function(){return e(this).attr("tabIndex")===0}).attr("tabIndex",-1),n.attr({"aria-expanded":"true","aria-hidden":"false"}).prev().attr({"aria-selected":"true",tabIndex:0})},_animate:function(e,t,n){var s,o,u,a=this,f=0,l=e.length&&(!t.length||e.index()",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},pending:0,_create:function(){var t,n,r,i=this.element[0].nodeName.toLowerCase(),s=i==="textarea",o=i==="input";this.isMultiLine=s?!0:o?!1:this.element.prop("isContentEditable"),this.valueMethod=this.element[s||o?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(i){if(this.element.prop("readOnly")){t=!0,r=!0,n=!0;return}t=!1,r=!1,n=!1;var s=e.ui.keyCode;switch(i.keyCode){case s.PAGE_UP:t=!0,this._move("previousPage",i);break;case s.PAGE_DOWN:t=!0,this._move("nextPage",i);break;case s.UP:t=!0,this._keyEvent("previous",i);break;case s.DOWN:t=!0,this._keyEvent("next",i);break;case s.ENTER:case s.NUMPAD_ENTER:this.menu.active&&(t=!0,i.preventDefault(),this.menu.select(i));break;case s.TAB:this.menu.active&&this.menu.select(i);break;case s.ESCAPE:this.menu.element.is(":visible")&&(this._value(this.term),this.close(i),i.preventDefault());break;default:n=!0,this._searchTimeout(i)}},keypress:function(r){if(t){t=!1,r.preventDefault();return}if(n)return;var i=e.ui.keyCode;switch(r.keyCode){case i.PAGE_UP:this._move("previousPage",r);break;case i.PAGE_DOWN:this._move("nextPage",r);break;case i.UP:this._keyEvent("previous",r);break;case i.DOWN:this._keyEvent("next",r)}},input:function(e){if(r){r=!1,e.preventDefault();return}this._searchTimeout(e)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(e){if(this.cancelBlur){delete this.cancelBlur;return}clearTimeout(this.searching),this.close(e),this._change(e)}}),this._initSource(),this.menu=e("