Documentation GPanel

Module import: from gpanel import *

Sprites Library

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
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 comlex
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) register 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)
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)
circle(radius) draws circle with center at current cursor position and given radius
fillCircle(radius) draws fiilled circle with center at current cursor position and given radius (fill color = pen color)
ellipse(a, b) draws ellipse with center at current cursor positon and given semiaxis
fillEllipse(a, b) draws ellipse with center at current cursor positon and given semiaxis (fill color = pen color)
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, x1, 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
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) returns a color reference of given value. Value examples: ("7FFED4"), ("Aqua-Marine"), (0x7FFED4), (8388564), (0.5, 1.0, 0.83), (128, 255, 212), ("rainbow", n) with n = 0..1, light spectrum

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
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)

Coordinate Transformations
(Window coordinates uses xmin, xmax, ymin, ymax; User coordinates are system-level pixel coordinates. Somewhat confusing.)
toWindowX(userX) x (in pixel) to x (in xmin, xmax)
toWindowY(userY) y (in pixel) to y (in ymin, ymax)
toWindowHeigh(userHeight) dx (in pixel) to dx (in xmin, xmax)
toWindowWidth(userWidth) dy (in pixel) to dy (in ymin, ymax)
toUserX(windowX)   x (in xmin, xmax) to x (in pixel)
toUserY(windowY)  y (in ymin, ymax) to y (in pixel)
toUserHeight(windowHeight) dx (in xmin, xmax) to dx (in pixel)
toUserWidth(windowWidth) dy (in ymin, ymax) to dy (in pixel)

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

Module import: from fitter import *

Curve fitting:
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
splinefit(xdata, ydata, nbKnots) fits a spline function that passes through nbKnots aequidistant data points. Returns the fitted data 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

Klasse 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)  

 

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,
client.disconnect() beendet die Verbindung mit dem Server
client.sendMessage(msg,) sendet die Information msg zum Server (als String, das Zeichen \0 (ASCII 0) dient als Endzeichen, automatisch transparent hinzugefügt und wieder entfernt).
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 that publishes and/or subcribes MQTT topics. The client does not yet connect to a MQTT broker.

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

 

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

creates a GameClient instance to handle game state information and message exchange.
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.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'