home

Documentation GPanel

Module import: from gpanel import *

Function Action
makeGPanel() creates a GPanel graphics window with coordinates (x = 0..1, y = 0..1). Current cursor at (0, 0)
makeGPanel(xmin, xmax, ymin, ymax) creates a GPanel graphics window with given float coordinate system. Current cursor at (0, 0)
makeGPanel(xmin, xmax, ymin, ymax, False) same as above, but invisible window (call visible(True), to make it visible)
makeGPanel(Size(width, height)) same as makeGPanel(), but window size user selectable (in pixels)
getScreenWidth() returns the screen width (in pixels)
getScreenHeight() returns the screen height (in pixels)
window(xmin, xmax, ymin, ymax) sets a new coordinate span
getWindow() returns reference to GWindow (JFrame)
drawGrid(x, y)

draws a coordinate grid with 10 ticks in range 0..x, 0..y. Label text depends if x, y or int or float

drawGrid(x, y, color)

same with given grid color

drawGrid(x1, x2, y1, y2)

same with given span x1..x2, y1..y2

drawGrid(x1, x2, y1, y2, color)

same with given grid color

drawGrid(x1, x2, y1, y2, x3, y3)

same with given number of ticks x3, y3 in x- and y-direction

drawGrid(x1, x2, y1, y2, x3, y3, color)

same with given grid color

drawPanelGrid(p, ...) same as drawGrid(...) with given GPanel reference (for several GPanels)
visible(isVisible) shows/hides the window
resizeable(isResizeable) makes the window resizable (default: not resizeable)
dispose() closes the window and releases resources
isDisposed() returns True, if window is disposed by title bar's close button or by calling displose()
bgColor(color) sets background color (X11 color string or Color type returned my makeColor())
title(text) sets text in title bar
makeColor(colorStr) returns color as Color type that corresponds to given X11 color string
windowPosition(ulx, uly) sets screen position (in pixels)
windowCenter() sets the window in the center of the screen
storeGraphics() stores the current graphics in internal image buffer
recallGraphics() renders the content of the internal image buffer
clearStore(color) erases the internal image buffer by painting it with given color
delay(time) pauses the program execution for given amount of time (in ms)
getDividingPoint(pt1, pt2, ratio) returns the point that divides the line from pt1 to pt2 with the given ratio (may be negative and greater than 1)
getDividingPoint(c1, c2, ratio) same with complex
toUser(winX, winY), toUserHeight(winHeight), toUserWidth(winWidth), toUserX(winX), toUserY(winY) Transformations from float to pixel coordinates
toWindow(userX, userY), toWindowHeight(userHeight), toWindowWidth(userWidth), toWindowX(userX), toWindowY(userY) Transformations from pixel to float coordinates
clear() clears the graphics window and sets the graphics cursor to (0, 0)
erase() clears the graphics window without changing the position of the graphics cursor
putSleep() pauses program execution until wakeUp() is called
wakeUp() resumes paused program execution
linfit(X, Y) performs a linear regression y = a*x+b with data in X- and Y-lists and returns (a, b)
addExitListener(onExit) registers the callback function onExit() that is called when the close button is hit. dispose() must be called, to close the GPanel window


Drawing

lineWidth(width) sets the line width (in pixel)
getLineWidth() returns current line width (in pixel)
setColor(color) sets die drawing color (X11 color string or Color type)
move(x, y) moves cursor to (x, y) without drawing a line
move(coord_list) moves cursor to point list [x, y] without drawing a line
move(c) moves cursor to complex(x, y) without drawiing a line
getPosX() returns the cursor's current x-coordinate
getPosY() returns the cursor's current y-coordinate
getPos() returns the cursor current x-, y-coordinates as list
draw(x, y), lineTo(x, y), lineto(x, y) draws line to (x, y) and updates cursor
draw(coord_list), lineTo(coord_list), lineto(coord_list) draws line to [x, y] and updates cursor
draw(c), lineTo(c), lineto(c) draws line complex [x, y] and updates cursor
line(x1, y1, x2, y2) draws line from (x1, y1) to (x2, y2) without modifying cursor
line(pt1, pt2) draws line from pt1 = [x1, y1] to pt2 = [x2, y2] without modifying cursor
line(c1, c2) draws line complex(x1, y1) to complex(x2, y2) without modifying cursor
line(li[p0, p1,...]) draws line path from starting point p0 of all points in list (or tupel)
arrow(x1, y1, x2, y2, size) draws an arrow from (x1, y1) to (x2, y2). size is the side length of the arrowhead triangle (default: 10)
arrow(pt1, pt2, size) draws an arrow from pt1 to pt2. size is the side length of the arrowhead triangle (default: 10)
arrow(c1, c2, size) draws an arrow from complex c1 to c2. size is the side length of the arrowhead triangle (default: 10)
doubleArrow(x1, y1, x2, y2, size) draws a double arrow from (x1, y1) to (x2, y2). size is the side length of the arrowhead triangles (default: 10)
doubleArrow(pt1, pt2, size) draws a double arrow from pt1 to pt2. size is the side length of the arrowhead triangles (default: 10)
doubleArrow(c1, c2, size) draws a double arrow from complex c1 to c2. size is the side length of the arrowhead triangles (default: 10)
circle(radius) draws circle with center at current cursor position and given radius (in x-coordinate units)
circle(x, y, radius), circle(center, radius) same, but with given center (list or complex)
fillCircle(radius) draws fiilled circle with center at current cursor position and given radius (fill color = pen color)
fillCircle(x, y, radius), fillCircle(center, radius) same, but with given center (list or complex)
ellipse(a, b) draws ellipse with center at current cursor positon and given semiaxis
ellipse(x, y, a, b), ellipse(center, a, b) same, bit with given center (list or complex)
fillEllipse(a, b) draws ellipse with center at current cursor positon and given semiaxis (fill color = pen color)
ellipse(x, y, a, b), ellipse(center, a, b) same, bit with given center (list or complex)
rectangle(a, b) draws rectangle with center at current cursor position and given width and height
rectangle(x1, y1, x2, y2) draws rectangle with center at current cursor position and given diagonal
rectangle(pt1, pt2) same with diagonal point lists
rectangle(c1, c2) same with diagonal complex
fillRectangle(a, b) draws filled rectangle with center at cursor and given width and height (fill color = pen color)
fillRrectangle(x1, y1, x2, y2) draws filled rectangle with center at cursor and given diagonal (fill color = pen color)
fillRectangle(pt1, pt2) same with diagonal point lists
fillRrectangle(c1, c2) same with diagonal complex
arc(radius, startAngle, extendAngle) draws arc with center at cursor and given radius, start and sector angle (0 to east, positive counterclockwise)
fillArc(radius, startAngle, extendAngle) same, but filled (fill color = pen color)
polygon(x_list, y_list) draws polygon with vertexes from x_list and y_list
polygon((li[pt1, pt2,..]) same with list of point lists pt1, pt2,...
polygon(li[c1, c2, c3,...]) same with list of complex c1, c2,...
fillPolygon(x-list, y-list) draws filled polygon with vertexes from x-list and y-list (fill color = pen color)
fillPolygon((li[pt1, pt2,..]) same with list of point lists pt1, pt2,...
fillPolygon(li[c1, c2, c3,...]) same with list of complex c1, c2,...
lowerPath, upperPath, hull = getHull(li[pt1, pt2,..]) returns point tuples lowerPath, upperPath and hull of the convex hull of pt1, pt2,...
quadraticBezier(x1, y1, xc, yc, x2, y2) draws quadratic Bezier-curve with 2 points (x1, y1), (x2, y2) and control point (xc, yc)
quadraticBezier(pt1, pc, pt2) same with points
quadraticBezier(c1, cc, c2) same with complex
cubicBezier(x1, y1, xc1, yc1, xc2, yc2, x2, y2) draws cubic Bezier-curve with 2 points (x1, y1), (x2, y2) and two control points (xc1, yc1), (yc2, yc2)
cubicBezier(pt1, ptc1, ptc2, pt2) same with points
cubicBezier(c1, cc1, cc2, c2) same with complex
triangle(x1, y1, x2, y2, x3, y3) draws a triangle with vertexes from x-, y-coordinates
triangle(pt1, pt2, pt3) same with point lists
triangle(c1, c2, c3) same with complex
triangle(li[pt1, pt2, pt3]) same with list of point lists
fillTriangle(x1, y1, x2, y2, x3, y3) draws a filled triangle with vertexes from x-, y-coordinates (fill color = pen color)
fillTriangle(pt1, pt2, pt3) same with point lists
fillTriangle(c1, c2, c3) same with complex
fillTriangle(li[pt1, pt2, pt3]) same with list of point lists
point(x, y) draws one single point (pixel) at (x, y)
point(pt) same with point list
point(complex) same with complex
fill(x, y, color, replacementColor)

fills a closed area with point (x, y) inside by replacing each pixel with given color by a pixel with replacementColor (floodfill)

fill(pt, color, replacementColor) same with point list
fill(complex, color,replacementColor) same with complex
image(path, x, y)

shows image in GIF , PNG oder JPG format at lower-left position x, y. The image path may be relative to the TigerJython folder, in the distribution JAR (folder sprites) or a URL starting with http://

image(path, pt) same with point list
image(path, complex) same with complex
image(bm, x, y) inserts GBitmap bm in GIF- , PNG- or JPG format with lower left vertex at (x, y)
image(bm, pt) same with point list
image(bm, complex) same with complex
imageHeighpath) returns the height of the image
imageWidth(path) returns the width of the image
enableRepaint(boolean) enables/disables automatic rendering of the offscreen buffer (default: enabled)
repaint() renders the offscreen buffer on screen (necessary if the automatic rendering is disabled)
setPaintMode() selects normal painting by overwriting the background
setXORMode(color) selects XOR-painting with given color. Painting twice removes without artefact
getPixelColor(x, y) returns color of pixel at (x, y) as Color type
getPixelColor(x, y).red returns the red component of color of pixel at (x, y)
getPixelColor(x, y).green returns the green component of color of pixel at (x, y)
getPixelColor(x, y).blue returns the blue component of color of pixel at (x, y)
getPixelColor(pt) same with point list
getPixelColor(complex) same with complex
getPixelColorStr(x, y) returns color of pixel at (x, y) as X11 color string
getPixelColorStr(pt) same with point list
getPixelColorStr(complex) same with complex
makeColor(value) creates a color. Value examples: ("7FFED4"), ("Aqua-Marine"), (0x7FFED4), (8388564), (0.5, 1.0, 0.83), (128, 255, 212), ("rainbow", n) with n = 0..1, light spectrum
makeColor(color, alpha) creates a transparent color for alpha between 0 and 1 (makeColor("red", 0.25) )
Node(center, text, size, borderSize, borderColor, textColor, bgColor, font) creates and draws an image with a (filled) circle and the center-aligned text. Defaults: size = 50, borderSize = 1, borderColor = "black", textColor = "black", bgColor = "white", font = Font("Courier", Font.PLAIN, 14). Returns the Node instance
Edge(node1, node2, lineWidth, color) creates and draws an non-directed edge between the two nodes. Defaults: lineWidth = 1, color = "black"
DirectedEdge(node1, node2, lineWidth, color, headSize) creates and draws a directed edge from node1 to node2.. Defaults: lineWidth = 1, color = "black", headSize = 10 (side lenght of triagle in pixels)
DoubleDirectedEdge(node1, node2, lineWidth, color, headSize) creates and draws a double directed edge between the two nodes. Defaults: lineWidth = 1, color = "black", headSize = 10 (side lenght of triagle in pixels)


Text

text(string) displays text starting at current cursor position
text(x, y, string) display text starting at given x-, y-coordinates
text(pt, string) same with point list
text(complex, string) same with complex
text(x, y, string, font, textColor, bgColor) displays text at given x-, y-coordinates with given font, text and background color
text(pt, string, font, textColor, bgColor) same with point list
text(complex,string, font, textColor, bgColor) same with complex
font(font) selects another text font (see below for font format)


Callbacks

makeGPanel(mouseNNN = onMouseNNN)
use a comma separator to register more than one
registers the callback function onMouseNNN(x, y) that is called when a mouse event happens. Values for NNN: Pressed, Released, Clicked, Dragged, Moved, Entered, Exited, SingleClicked, DoubleClicked
isLeftMouseButton(),
isRightMouseButton()
returns True, if the event is caused by the left/right mouse button
makeGPanel(keyPressed = onKeyPressed) registers the callback onKeyPressed(keyCode) that is called when a keyboard key is hit. keyCode is a unique integer value that identifies the key
getKeyModifiers() returns an integer code for special keyboard keys (shift, ctrl, etc., also combined)
makeGPanel(closeClicked = onCloseClicked) registers the callback onCloseClicked() that is called when the title bar close button is hit. The window must be closed manually by calling dispose()
showSimulationBar(NNN = onNNN)

shows a dialog window with buttons 'Step', 'Run'/'Pause', 'Reset' and a slider to adjust the simulation period. The following callbacks can be registered: start, pause, step, reset, change(parameter: simulationPeriod), loop, exit (close button hit). loop is invoked in every simulation cycle by the simulation thread

showSimulationBar(ulx, uly, initPeriod, NNN = onNNN) same, but with dialog screen position (upper left corner) and simulation period (default: 100)
hideSimulationBar() closes the dialog and frees all resources


Keyboard

getKey()   returns the character (as string) of the last key pressed (empty, if illegal key)
getKeyCode()   returns the key code of the last key pressed
getKeyWait() stops the program until a key is pressed and returns the character (as string) of the key (empty, if illegal key)
getKeyCodeWait() stops the program until a key is pressed and returns the key code of the key
getModifiers() returns special code if ctrl/alt/shift key is pressed
getModifiersText() returns verbose description if ctrl/alt/shift key is pressed
kbhit() returns True, if a key was hit since the last call of getKey() or getKeyCode()


GUI Components

add(component)   inserts a GUI component near the top border of the window
validate()   repaints the window after a component has been added


Status Bar

addStatusBar(height)   adds a status bar at the bottom of the window with given height (in pixels)
setStatusText(text)   displays text in the status bar (old text is erased)
setStatusText(text, font, color) displays text in the status bar with given font and color (old text is erased)


Font Format

Font(name, style, size) creates a new font with given name, style and size
name a string with a font name available on the system, e.g. "Times New Roman", "Arial", "Courier"
style One of the stype constants: Font.PLAIN, Font.BOLD, Font.ITALIC, may also be combined: Font.BOLD + Font.ITALIC
size an integer with an available font size in pixels, e.g. 12, 16, 72

 

Dialogs

msgDlg(message) opens a modal dialolg with an OK button and given message
msgDlg(message, title = title_text) same with title text
inputInt(prompt)

opens a modal dialog with OK/Cancel buttons. OK returns integer (the dialog is shown again, if no integer is entered). Cancel or Close terminate the program. The named parameter init sets an initialising value

inputInt(prompt, False)

same, but Cancel/Close do not terminate, but returns None

inputFloat(prompt) opens a modal dialog with OK/Cancel buttons. OK returns float (the dialog is shown again, if no float is entered). Cancel or Close terminate the program. The named parameter init sets an initialising value
inputFloat(prompt, False) same, but Cancel/Close do not terminate, but returns None
inputString(prompt) opens a modal dialog with OK/Cancel buttons. OK returns string. Cancel or Close terminate the program. The named parameter init sets an initialising value
inputString(prompt, False) same, but Cancel/Close do not terminate, but returns None
input(prompt) opens a modal dialog with OK/Cancel buttons. OK returns integer, float or string. Cancel or Close terminate the program. The named parameter init sets an initialising value
input(prompt, False) same, but Cancel/Close do not terminate, but returns None
askYesNo(prompt)

opens a modal dialog with Yes/No buttons. Yes returns True, No returns False. Cancel or Close terminate the program

askYesNo(prompt, False) same, but Close do not terminate, but returns None

 

class GBitmap

bm = GBitmap(width, height) creates an empty bitmap with given horizontal and vertical number of pixels
bm = getImage(filename)

creates a bitmap that holds the picture from given file (formats: jpg, bmp, png, gif)

bm = getBitmap() returns a copy of the bitmap from the current GPanel content
bm.getWidth() returns the width of the bitmap (in pixels)
bm.getHeight() returns the height of the bitmap (in pixels)
bm.getPixelColor(x, y) returns the color of the pixel at (x, y) (as color type)
bm.getPixelColor(pt) returns the color of the pixel at pt = [x, y] (as color type)
bm.getPixelColorStr(x, y) returns the color of the pixel at (x, y) (as X11 color string)
bm.getPixelColorStr(pt) returns the color of the pixel at pt = [x, y] (as X11 color string)
bm.setPixelColor(x, y, color) sets the color of pixel at (x, y) (color type)
bm.setPixelColor(pt, color) sets the color of pixel at pt =[x, y] (color type)
bm.setPixelColorStr(x, y, color) sets the color of pixel at (x, y) (X11 color string))
bm.setPixelColorStr(pt, color) sets the color of pixel at pt =[x, y] (X11 color string)
bm = readImage(data)

converts the binary image data stream to a bitmap (data in jpg, gif, bmp, png format as string type)

s = imageToString(bm, type)

converts the bitmap to a binary image data stream (string) (type = "bmp", "gif", "jpg", "png)

save(bm, filename, type) writes the bitmap image to a file (type = "bmp", "gif", "jpg", "png)
saveData(data, filename) writes image from binary data stream (string) to a file
bm1 = paste(bm, bmReplace, x, y)

replaces a part of the image at position (x, y) with bmReplace. Returns a new bitmap

bm1 = crop(bm, x1, y1, x2, y2) returns the bitmap image from the given rectangle
bm1 = scale(bm, factor, angle) scales the image with the given factor and rotates it by a given angle (in degrees clockwise). Returns a new bitmap
bm1 = floodFill(bm, x, y, oldColor, newColor) fills the closed area with uniformly colored pixels around the given point (x, y) with newColor. Returns a new bitmap


Documentation Sound

Sound

playTone(freq) plays tone mit given frequency (in Hz) and duration 1000 ms (blocking function)
playTone(freq, blocking=False) same, but not-blocking function, used to play several tones at (about) the same time
playTone(freq, duration) plays tone with given frequency and given duration (in ms)
playTone([f1, f2, ...]) plays several tones in a sequence with given frequency and duration 1000 ms
playTone([(f1, d1), (f2, d2), ...]) plays serveral tones in a sequence with given frequency and given duration
playTone([("c", 700), ("e", 1500), ...]) plays serveral tones in a sequence with given (Helmholtz) pitch naming and duration.
Supported are: great octave, one-line to three-line octave (range C, C# up to h'''
playTone([("c", 700), ("e", 1500), ...], instrument = "piano") same, but selects instrument type. Supported are: piano, guitar, harp, trumpet, xylophone, organ, violin, panflute, bird, seashore, ... (see MIDI specifications)
playTone([("c", 700), ("e", 1500), ...], instrument = "piano", volume=10) same, but selects sound volume (0..100)

 

Module import: from soundsystem import *

Playing

Function Action
samples = getWavMono(filename)

returns list of integer sound data from the given monaural sound file. With "wav/xxx.wav" loads files from the wav folder of tigerjython2.jar

samples = getWavStereo(filename) returns list of integer sound data from the given binaural sound file. With "wav/xxx.wav" loads files from the wav folder of tigerjython2.jar
getWavInfo(file) returns string with audio information about the given sound file
openSoundPlayer(filename) opens a sound player from the given sound file. The sound is played using the following sound functions. With "wav/xxx.wav" loads files from the wav folder of tigerjython2.jar
openSoundPlayer(buffer) same, but loads sound samples in WAV format from a byte array (type array.array)
openMonoPlayer(samples, sampleRate) creates a monaural sound player to play the list of integer values with given sample rate. The sound is played once using the play() function
openStereoPlayer(samples, sampleRate) creates a stereo sound player to play the list of integer values with given sample rate. The sound is played once using the play() function
openSoundPlayerMP3(filename) same as openSoundPlayer(), but with MP3 sound
openMonoPlayerMP3(filename) same as openMonotPlayer(), but with MP3 sound
openStereoPlayerMP3(filename) same as openStereoPlayer(), but with MP3 sound
play() plays sound from current position and returns immediately
blockingPlay()

plays sound from current position but blocks until it is finished

advanceFrames(n)

advances the current position for the given number of samples

advanceTime(t)

advances the current position for the given time interval

getCurrentPos()

returns the current position

getCurrentTime()

returns the current playing time

rewindFrames(n)

moves the current position back for the given number of samples

rewindTime(t) moves the current position back for the given time interval
stop() hält das Abspielen an und setzt die aktuelle Abspielposition an den Anfang
setVolume(v) sets the sound volume (v = 0..100)
isPlaying() return True, if the sound is still playing
mute(bool) if False, the sound is not audible; if True, it is audible again
playLoop() plays the sound in an endless loop
replay() restarts the sound
delay(time) stops the program for the given time (in milliseconds), to insert intermission

 

Sound files in TigerJython distribution

(Format: WAV PCM 16 bit mono)
Filename Sample rate (Hz) Description
wav/bird.wav 22050 Short bird twitter
wav/boing.wav 22050 Hit sound
wav/cat.wav 22050 Meaw
wav/click.wav 22050 Click
wav/dog.wav 22050 Bark
wav/dummy.wav 40000 Sine wave of 500 Hz and 1500 Hz (half amplitude)
wav/explode.wav 22050 Explosion
wav/fade.wav 22050 Fading away
wav/flute.wav 20000 Flute playing G2 (352 Hz)
wav/harris.wav 20000 Voice speaking "harris"
wav/mmm.wav 22050 Short "mmm" to get hungry
wav/notify.wav 22050 Short notification sound
wav/oboe.wav 20000 Oboe playing G2 (352 Hz)
ping.wav 22050 Short ping notification

 

Recording/Saving

openMonoRecorder() opens a monaural sound recorder
openStereoRecorder() opens a binaural sound recorder
capture() starts the recording
stopCapture() terminates the recording
getCapturedBytes() returns the recorded sound samples as byte list
getCapturedSound() returns the recorded sound as integer list (for stereo the channels are alternated)
writeWavFile(samples, filename) writes the sound to a WAV formatted file

 

Fast Fourier Transform (FFT)

fft(samples, n)

transforms the first n values of the given list of sound samples (floats). Returns a list of n//2 aequidistant spectral values (floats). If fs is the sampling rate, these values lay between 0 and fs/2 with mutual distance fs /n (resolution)

fft_db(samples, n) same, but returns the sprectral values in decibel 20*log(v)
fft_filter(ydata, cutoff, isLowpass)

performs filtering by Fourier transformation. For isLowPass = True the upper part of the spectrum is nulled out, for isLowpoass = False the lower part is nulled out. Then the spectrum is transformed back to time domain by an inverse Fourier transformation. cutoff in range 0...len(ydata) determines the cutoff frequency fc. For cutoff = len(ydata) the cutoff frequency is fs / 2 (fs: sampling frequency)

toAequidistant(xrawdata, yrawdata, deltax) returns two lists xdata, ydata with aequidistant values separated by deltax (linear interpolation)
sine(A, f, t) Sine wave with amplitude A and frequency f (phase 0) for every float value t
square(A, f, t) Square wave with amplitude A and frequency f (phase 0) for every float value t
sawtooth(A, f, t) Sawtooth wave with amplitude A and frequency f (phase 0) for every float value t
triangle(A, f, t) Triangle wave with amplitude A and frequency f (phase 0) for every float value t
chirp(A, f, t) Sine wave with amplitude A and time-linear increasing frequency (starting value f) for every float value t

 

Curve fitting:

Module import: from fitter import *

Function Action
coeffs = polynomfit(xdata, ydata, n) fits a polynom of order n and returns the fitted values in ydata. Return value: list with n + 1 polynom coefficients
spline = splinefit(xdata, ydata) fits a spline function that passes the data points. Returns the spline function with definition interval min(xdata)..max(xdata). Outside spline(x) returnes 0
fft_filter(ydata, cutoff, isLowPass) applies a low or high pass filter to the aequidistant data points. cutoff in range 0..n, where n = len(ydata). Return values in ydata
functionfit(func, derivatives, initialGuess, xdata, ydata) fits the function func(x, param) with n parameters in list param. derivatives(x, param) returns a list with the values of the partial derivatives to the n parameters. initGuess is a list with n guessed values for the n parameters
functionfit(func, derivatives, initialGuess, xdata, ydata, weights) same but with a list weights that determines the relative weights of the data points
toAequidistant(xrawdata, yrawdata, deltax)

returns two lists xdata, ydata with aequidistant values separated by deltax (linear interpolation)


TCP Client/Server Library:

Module import: from tcpcom import *

Class TCPServer

server = TCPServer(port, stateChanged, isVerbose = False) creates a TCP socket server that listens on TCP port for a connecting client. State changes are notified by the callback stateChanged(). For isVerbose = True, debug messages are written to output window
stateChanged(state, msg)

Callback called at state change events.
state: TCPServer.PORT_IN_USE, msg: port
state: TCPServer.CONNECTED, msg: IP address of client
state: TCPServer.LISTENING, msg: port
state: TCPSever.TERMINATED, msg: empty
state: TCPServer.MESSAGE, msg: message received from client (string)

server.disconnect() closes the connection with the client and enters the LISTENING state
server.isConnected() True, if a client is connected to the server
server.terminate() closes the connection and terminates the LISTENING state. Releases the IP port
server.isTerminated() True, if the server has been terminated
server.sendMessage(msg) sends the information msg to the client (as string, the character \0 (ASCII 0) serves as end of string indicator, it is transparently added and removed)
TCPServer.getVersion() returns the module version as string

 

Class TCPClient

client = TCPClient(ipAddress, port, stateChanged, isVerbose = False)

creates a TCP socket client prepared for a connection with a TCPServer at given address (string) and port (integer). State changes are notified by the callback stateChanged(). For isVerbose = True, debug messages are written to the output window

stateChanged(state, msg) Callback called at state change events.
state: TCPClient.CONNECTING, msg: IP address:port of server
state: TCPClient.CONNECTION_FAILED, msg: IP address:port of server
state: TCPClient.CONNECTED, msg: IP address:port of server
state: TCPClient.SERVER_OCCUPIED, msg: IP address:port of server
state: TCPClient.DISCONNECTED, msg: empty
state: TCPClient.MESSAGE, msg: message received from server (string)
client.connect() creates a connection to the server (blocking until timeout). Returns True, if the connection is established; otherwise returns False
client.connect(timeout) same, but with timeout (in s) to establish the connection
client.isConnecting() True during a connection trial
client.isConnected() True, if the client is connected to a server
client.disconnect() closes the connection with the server
client.sendMessage(msg, responseTime) sends the information msg to the server (as string, the character \0 (ASCII 0) serves as end of string indicator, it is transparently added and removed). For responseTime > 0 the method blocks and waits for maximum responseTime seconds for a server reply. Returns the message or None, if a timeout occured
TCPClient.getVersion() returns the module version as string

 

Class HTTPServer (inherited from TCPServer)

server = HTTPServer(requestHandler, serverName = "PYSERVER", port = 80, isVerbose = False)

creates a HTTPServer (Web server, inherited from TCPServer) that listens for a connecting client on given port (default = 80). Starts a thread that handles and returns HTTP GET requests.
The HTTP response header includes the given server name (default: "PYSERVER").
Only text responses are supported.

requestHandler() is a callback function called when a GET request is received.
Signature:
msg, stateHandler = requestHandler(clientIP, filename, params)
Parameters:
     clientIP: the client's IP address in dotted format
     filename: the requested filename with preceeding '/'
     params: a tuple with format:
          ((param_key1, param_value1), (param_key2, param_value2), ...) (all items are strings)
Return values:
     msg: the HTTP text response (the header is automatically created)
     stateHandler: a callback function that is invoked immediately after the reponse is sent

If stateHandler = None, nothing is done. The function may include longer lasting server actions or a wait time, if sensors are not immediately ready for a new measuremen.

Call terminate() to stop the server. The connection is closed by the server at the end of each response. If the client connects, but does not send a request within 5 seconds, the connection is closed by the server

getClientIP() returns the dotted IP of a connected client. If no client is connected, returns empty string
getServerIP() returns the server's IP address (static method)
(all methods of TCPServer)  


Class HTTPClient

Funktion Aktion
HTTPClient.getRequest(url, data = None)

sends a GET request to the server. url is either "http://serveraddress?key1 = value1&key2 = value2 ..." or just "http://serveraddress" and data is a directory {key1: value1, key2: value2, ..}. In this case, key and value are automatically URL encoded. For SSL (port: 443) http: is replaced by https :.
The return value is the HTTP response (without header). If an error occurs, the error description is returned

HTTPClient.postRequest(url, data = None) sends a POST request to the server. url is either "http://serveraddress?key1 = value1 & key2 = value2 ..." or just "http://serveraddress" and data is a directory {key1: value1, key2: value2, ..}. In this case, key and value are automatically URL encoded. For SSL (port: 443) http: is replaced by https :.
The return value is the HTTP response (without header). If an error occurs, the error description is returned. If an error occurs, the error description is returned
HTTPClient.deletetRequest(url, data = "") sends a DELETE request to the server. url is "http://serveraddress" and data is a string containing the file path of the file to delete. For SSL (port: 443), http: is replaced by https :.
The return value is the HTTP response (without header). If an error occurs, the error description is returned
HTTPClient.pushover(token_key, user_key, title, message)

sends a push request to the pushover server api.pushover.net with given token key, user key, title and message. For verbose = True, debug information is printed. The return value is the HTTP response (without header). If an error occurs, the error description is returned


class ThingSpeakChannel

Function Action
chn = ThingSpeakChannel(channelId, readKey, writeKey, userKey, verbose = False)

creates an instance of the ThinkSpeakChannel class for communication with an existing channel on the cloud server www.thingspeak.com. The parameters correspond to the values received from the server during the channel definition. With verbose = True, debug informationen are written to the console. userKey is assigned to the user account and not to the channel (User API Key)

chn.getData(nbEntries = -1, includeDate = True)

returns the last nbEntries records as list of dictionaries [{fieldId: value} ...] (fieldId = 1..8). For nbEntries = -1, all records are returned. For includeDate = True, the field 'data', which contains the date-time of the record's creation, is also returned. All values are strings. In case of error, None is returned

chn.getTable(nbEntries = -1, includeDate = True)

the same, but returns an instance of DbTable with the table values. In case of error, an empty table is returned

 

chn.show(nbEntries = -1, includeDate = True) the same, but shows the table contents in the console
chn.getLastValue(fieldId = 1)

returns the value of the last record with given fieldId (1..8). In case of error or if the table is empty, None is returned

chn.getFields()

returns a dictionary with the fields defined in the channel and their names: {'field1': <field name 1>, 'field2' :, <field name 2> ..}. In case of error, None is returned

chn.insert(data, timeout = 20)

makes a new table entry and returns True, if successful. data is either a single value (number or string) or a dictionary {fieldId: value, ...} for an entry in multiple fields. Fields that have no value are set to None. For free accounts, a new entry is only allowed every 15 seconds, for payed accounts every second; if the server is not yet ready to accept new data, the insertion trial is repeated every second until the timeout (in s) is reached and False is returned

chn.clear()
clears all table entries. If successful returns True

 

Bluetooth Client/Server Library

Module import: from btcom import *

class BTServer

server = BTServer(serviceName, stateChanged, isVerbose = False) creates a Bluetooth server that exposes the RFCOMM service with name serviceName. State changes are notified by the callback stateChanged(). For isVerbose = True, debug messages are written to the output window
stateChanged(state, msg)

Callback called at state change events.
state: "LISTENING" , msg: empty
state: "CONNECTED", msg: remote info: bluetooth name (MAC address)
state: "TERMINATED", msg: empty
state: "MESSAGE", msg: message received

server.disconnect() closes the connection with the client and enters the LISTENING state
server.isConnected() True, if a client is connected to the server
server.terminate() closes the connection and terminates the LISTENING state. Releases internal resources
server.isTerminated() True, if the server has been terminated
server.sendMessage(msg) sends the information msg to the client (as string, the character \0 (ASCII 0) serves as end of string indicator, it is transparently added and removed)
BTServer.getVersion() returns the module version as string


class BTClient

client = BTClient(stateChanged, isVerbose = False)

creates a Bluetooth client prepared for a connection with a
BTServer. State changes are notified by the callback stateChanged(). For isVerbose = True, debug messages are written to the output window

client.findServer(serverName, timeout) performs a device inquiry for the given server Bluetooth name. Returns the tuple serverInfo: ("nn:nn:nn:nn:nn:nn", channel) , e.g. ("B8:27:EB:04:A6:7E", 1). If the server is not found, None is returned. The search is repeated until the timeout (in s) is reached
client.findService(serviceName, timeout)

performs a service inquiry for a Bluetooth server exposing the given RFCOMM service. Returns the tuple serverInfo: ("nn:nn:nn:nn:nn:nn", channel) , e.g. ("B8:27:EB:04:A6:7E", 1). If the service is not found, None is returned. The search is repeated until the timeout (in s) is reached

stateChanged(state, msg) Callback called at state change events.
state: "CONNECTING" , msg: server info (MAC address, Bluetooth channel)
state: "CONNECTED" , msg: server info
state: "CONNECTION_FAILED", msg: sever info
state: "DISCONNECTED", msg: empty
state: "MESSAGE", msg: message received
client.connect(serverInfo, timeout) Performs a connection trial to the server with given serverInfo. If the connection trial fails, it is repeated until the timeout (in s) is reached. Returns True, if the connection is established; otherwise False is returned. serverInfo is a tuple with the MAC address and channel number ("nn:nn:nn:nn:nn:nn", channel) , e.g. ("B8:27:EB:04:A6:7E", 1)
client.isConnecting() returns True during the connection trial
client.isConnected() returns True, if the client is connected to a server
client.disconnect() closes the connection
client.sendMessage(msg) sends the information msg to the client (as string, the character \0 (ASCII 0) serves as end of string indicator, it is transparently added and removed)
BTClient.getVersion() returns the module version as string

 

MQTT Client Library

Module import: from mqttclient import *

class MQTTClient

client = MQTTClient(messageReceived = None, username = "", password = "")

creates a MQTTClient instance that publishes and/or subcribes MQTT topics. The client does not yet connect to a MQTT broker. The client handles ping requests and reconnection automatically.

messageReceived(topic, message) is a callback function triggerd by incoming messages and
running in a separate thread. If None, no message notifications are triggered, e.g. for a client that only publishes topics. username is used to log into the MQTT broker (empty, if no user authentication is necessary). password is the password used to log into the MQTT broker (empty, if no user authentication is necessary)

client.connect(host, port = 1883, keepalive = 60)

starts a connection trial to the given MQTT broker at given port. host is the broker's IP address and port its IP port where it is listening (default: 1883).
keepalive is the maximum period in seconds between communications with the broker.
If no other messages are exchanged, this is the time period for ping messages to the broker (default: 60 s). Returns True, if the connection is successful; otherwise False

client.disconnect() disconnects the client from the broker
client.publish(topic, payload, qos = 0, retain = False) sends a message with given topic and payload to the broker. payload is a string (if an int or float is given, it is converted to a string). qos is the quality of service level (number 0, 1, 2, default: 0). retain determines, if the message is the “last known good”/retained message for the topic (default: False)
client.subscribe(topic, qos = 0) subscribes the client to one or more topics. topic is a string or a list of tuples of format (topic, qos). qos is the quality of service level (number 0, 1, 2. default: 0); not used, if topic is a list of tuples'
client.setVerbose(verbose) enables/disables logger information printed at stdout

The module paho-mqtt is also available. See API-Reference.
Example:

import paho.mqtt.client as mqtt
client = mqtt.Client()

 

class GameClient

client = GameClient(stateChanged, messageReceived, topic = "/ch/aplu/mqtt/gameclient")

creates a GameClient instance to handle game state information and message exchange for two players games. stateChanged(state) is a callback function that is triggered when the game state is modified. state values: 'CONNECTING' (while connecting to broker), 'CONNECTED' (if connected to the broker, but waiting for a partner), 'READY' (both players are ready to play), 'DISCONNECTED' (the partner disconnected). messageReceived(msg) is a callback function that is triggered when a message arrived. topic is the MQTT topic used for information exchange (default: /ch/aplu/mqtt/gameclient)

client.setName(name) sets the player's name that is communicated to the partner when getting READY
client.connect(host, port = 1883)

enganges a connection trial to the MQTT broker with the given IP address and port (default: 1883)

client.sendMessage(text) sends a text information to the partner
client.disconnect() disconnects the client from the broker
client.getState() returns the current state of the GameClient. (One of 'IDLE', 'CONNECTING', 'CONNECTED', 'READY', 'DISCONNECTED'
client.getPartnerName() returns the game partner's name that is communicated from the partner when getting READY (empty if not yet READY)
getPartnerAddress() returns the game partner's IP address (in dotted format) that is communicated from the partner when getting READY (empty if not yet READY)

Weather data:

Module import: import weather

Function Action
info = weather.request(city, key = defaultKey, lang = 'en')

makes a weather data request at http://openweathermap.org for the given location. The given authorization key is used. This can be obtained free of charge on this host. (If the parameter is omitted, a default key is used, which allows a maximum of 60 requests / min for all users.)

Return value: Dictionary with the fields:

"status" "OK" or error string describing the error, e.g. "City not found"
"temp" Temperature in °C (float)
"pressure" Air pressure in hPa (mbar) (float)
"humidity" Humitiy in % (int)
"temp_min" Minimum daily temperature in °C (float)
"temp_max" Maximum daily temperature in °C (float)
"description" Weather description (string, language defined by parameter lang)
"sunrise" Sunrise in Universal Time (UTC) (string)
"sunset" Sunset in Universal Time (UTC) (string)
"datetime" Date-Time of weather recording (UTC) (string)

home