Usage

Installation

The easiest way to install the framework is pip: $ pip install snapext.

Alternatively, if you’re feeling brave, you could compile the module from source by using $ python setup.py install.

Creating a Snap! extension

We’ll go through making a theoretical extension that controls spaceship doors from Snap!.

Setting up your extension

Import the snapext module in the first line of your file.

import snapext

After that, import other modules you need for your extension (hardware control, bluetooth, etc.) and set up whatever else you need for the extension.

import snapext
doors_open = True

Then set handler to snapext.SnapHandler.

import snapext
doors_open = True
handler = snapext.SnapHandler

Next, we’ll enable your extension to send data and receive commands from Snap!.

Receiving Commands

Here’s the general structure for commands.

@handler.route('/commandurl')
def command(input):
    command_with(input)

Line 1 defines your command URL. On line 2, define a function that takes either no input, or an input from the URL accessed from Snap!. On line 3, run command(s) for your extension.

Example:

@handler.route('/doors/set')
def set_doors(is_open):
    global doors_open
    print is_open
    if is_open:
        doors_open = True
        # Open spaceship doors
    else:
        doors_open = False
        # Close spaceship doors -- don't let humans in!

Returning Data

The structure for returning data is almost exactly the same as receiving commands.

@handler.route('/returndata')
def returndata(input):
    return result_of_function_with(input)

Everything is the same as receiving commands, except for line 3, which uses a return statement. Example:

@handler.route('/doors/is_open')
def get_doors():
    return doors_open

Running the main loop

One last step. Run the snapext.main function with a port number of your choice.

snapext.main(handler, [your port number])

Example:

snapext.main(handler, 47543)

Table Of Contents

This Page