Functions

call

call(rawOpcodes, *functionArgs)

Call embedded C code.

This function is for advanced users only. There is a separate Application Note that covers how to use this advanced feature.

Parameters
  • rawOpcodes (str) – Machine code that implements the function to be called.

  • *functionArgs (arbitrary argument list) – Parameters depend on the actual function implemented by rawOpcodes.

callback

callback(callback, remoteFunction, *remoteFunctionArgs)

It is easy to invoke functions on another node using the rpc() built-in function; however, to get data back from that node, you either need to put a script in that node to explicitly send the value back, or use the callback() function.

Parameters
  • callback (str) – Specifies which function to invoke on the originating node, passing in the return value of the remote function.

  • remoteFunction (str) – Specifies which function to invoke on the remote node.

  • *remoteFunctionArgs (arbitrary argument list) – Used if the remote function takes any parameters.

Returns

Normally returns True, but it does not mean your RPC request was successfully sent and received

Returns False only if it was unable to attempt the Remote Procedure Call (for example, if the node is low on memory).

Return type

bool

Examples

Imagine having a function like the following in SNAP node A:

def showResult(obj):
    print str(obj)

Invoking callback('showResult', 'functionOnB') on node B will cause function showResult() to get called on node A with the result of function functionOnB() on remote node B.

The remoteFunction parameter can take parameters, so node A could also invoke the following on node B by passing 0 to the readAdc() function:

callback('showResult', 'readAdc', 0)

Node B would invoke readAdc(0) and then remotely invoke showResult(the-actual-ADC-reading-from-readAdc(0)) on node A.

The callback() function is most commonly used with the rpc() function:

rpc(nodeB, 'callback', 'showResult', 'readAdc', 0)

Essentially, callback() allows you to ask one node to do something and then tell you how it turned out.

Note

Even if you do not have a script that explicitly sends the return value back, you still must have some script in a node before you can call any function, including any of the built-in functions by name.

See also

callout

callout(nodeAddress, callback, remoteFunction, *remoteFunctionArgs)

This function is similar to callback(), but instead of the final result being reported back to the originating node, you explicitly provide the address of the target node.

Parameters
  • nodeAddress (str) – Specifies the SNAP address of the target node that is to receive the callback.

  • callback (str) – Specifies which function to invoke on the target node passing in the return value of the remote function.

  • remoteFunction (str) – Specifies which function to invoke on the remote node.

  • *remoteFunctionArgs (arbitrary argument list) – Used if the remote function takes any parameters.

Returns

Normally returns True, but it does not mean your RPC request was successfully sent and received.

Returns False only if it was unable to attempt the Remote Procedure Call (for example, if the node is low on memory).

Return type

bool

Examples

Node A could invoke the following on node B, which would automatically invoke node C:

callout(nodeC, 'showResult', 'readAdc', 0)

Node B would invoke readAdc(0) and then remotely invoke showResult(the-actual-ADC-reading-from-readAdc(0)) on node C.

The callout() function is most commonly used with the rpc() function:

rpc(nodeB, 'callout', nodeC, 'showResult', 'readAdc' ,0)

Essentially, callout() allows you to have one node ask another node to do something, and then tell a third node how it turned out.

Note

To understand this function, you should first be comfortable with using the rpc() and callback() built-ins.

See also

chr

chr(number)

Translates an ASCII code into a single-character string.

Parameters

number (int) – ASCII code as an integer.

Returns

A single-character string based on the number given.

Return type

str

Example

Ways to obtain the string 'A':

chr(0x41) # returns the string 'A'
chr(65)   # so does this

crossConnect

crossConnect(dataSrc1, dataSrc2)

Cross-connect SNAP data sources.

Parameters
  • dataSrc1 (int) – SNAP data source.

  • dataSrc2 (int) – SNAP data source.

Returns

None

See also

dmCallout

dmCallout(dstAddrs, dstGroups, ttl, delayFactor, callback, remoteFunction, *remoteFunctionArgs)

New in version SNAP 2.7.

Warning

If you provide a dstAddrs that is not a multiple of three characters in length, the call will fail and no message will be sent to any node.

Parameters
  • dstAddrs (str) – A string containing concatenated addresses of the target nodes that are to receive the final (result) function call.

  • dstGroups (str) – Specifies which nodes should receive the outgoing message, based on their multicast processed groups. By default, all nodes belong to the broadcast group 0x0001.

  • ttl (int) – Specifies the Time To Live (TTL) for the request. This specifies how many hops the message is allowed to make before being discarded.

  • delayFactor (int) – Provides a mechanism to allow remote nodes to stagger their responses to the message. The parameter should be a one-byte integer specifying the amount of time, in milliseconds, that should pass between node responses, among the nodes targeted by the request. Setting this parameter to zero allows all remote nodes to respond immediately, which may cause packet loss due to interference.

  • callback (str) – Specifies which function to invoke on the originating node, passing in the return value of the remote function.

  • remoteFunction (str) – Specifies which function to invoke on the remote node.

  • *remoteFunctionArgs (arbitrary argument list) – Used if the remote function takes any parameters.

Returns

This function normally returns True; however, it does not mean your RPC request was successfully sent and received.

It returns False only if it was unable to attempt the Remote Procedure Call (for example, if the node is low on memory or the RPC was too large to send).

Return type

bool

Note

As with a dmcastRpc(), any node that finds its address when it receives the multicast message will act on the message (assuming that the multicast processed groups setting is compatible). Also as with dmcastRpc(), if you pass an empty string as the dstAddrs parameter, the outgoing message will behave as a regular mcastRpc() call.

dmcastRpc

dmcastRpc(dstAddrs, dstGroups, ttl, delayFactor, remoteFunction, *remoteFunctionArgs)

New in version SNAP 2.6.

Directed multicast provides a means to send an RPC call to a list of remote nodes without incurring the route discovery overhead necessary for addressed RPC calls.

Parameters
  • dstAddrs (str) –

    A string containing concatenated addresses for any nodes you wish to act on the directed multicast.

    If you provide an empty string (""), all remote nodes that receive the message that would otherwise act on the message (subject to the dstGroups parameter and the existence of the function in the remote node’s script) will act on the request as though the call were a regular mcastRpc() call; however, in this case added features available only for directed multicast (such as information available through several getInfo() calls) are also available.

  • dstGroups (str) – Specifies which nodes should respond to the request. By default, all nodes belong to the broadcast group 0x0001.

  • ttl (int) – Specifies the Time To Live (TTL) for the request. This specifies how many hops the message is allowed to make before being discarded.

  • delayFactor (int) – Provides a mechanism to allow remote nodes to stagger their responses to the request. The parameter should be a one-byte integer specifying the amount of time, in milliseconds, that should pass between node responses, among the nodes targeted by the request. Setting this parameter to zero allows all remote nodes to respond immediately, which may cause packet loss due to interference.

  • remoteFunction (str) – Specifies which function to invoke on the remote node.

  • *remoteFunctionArgs (arbitrary argument list) – Used if the remote function takes any parameters.

Returns

This function normally returns True; however, it does not mean your RPC request was successfully sent and received.

It returns False only if it was unable to attempt the Remote Procedure Call (for example, if the node is low on memory or the RPC was too large to send).

Return type

bool

Warning

If you provide a dstAddrs that is not a multiple of three characters in length, the call will fail and no message will be sent to any node.

See also

eraseImage

eraseImage()

This function is used by Portal and SNAPconnect as part of the script upload process and is not normally used by user scripts. Calling this function automatically invokes the resetVm() function before erasing the image (otherwise the SNAPpy VM would still be running the script, as you erased the image out from under it).

Returns

None

errno

errno()

Returns the most recent error code from the SNAPpy Virtual Machine (VM), clearing it out as it does so.

If you receive an UNSUPPORTED_OPCODE, UNRESOLVED_DEPENDENCY, BAD_GLOBAL_INDEX, or BAD_CONST_INDEX error, please contact Synapse Wireless support and provide your SNAPpy script. These errors should not be reachable with a SNAPpy script, unless you are manipulating memory behind-the-scenes with pokes or with callable C strings.

The EXCEEDED_MAX_BLOCK_STACK and EXCEEDED_MAX_OBJ_STACK errors have been retired from SNAPpy code and can no longer be generated.

Returns

The most recent error code.

Return type

int

The possible error codes are:

Value

Enumeration

Possible Cause

0

NO_ERROR

1

OP_NOT_DEFINED

Are you trying to add or compare things where that is not an option, such as adding two functions, or two Nones?

2

UNSUPPORTED_OPCODE

3

UNRESOLVED_DEPENDENCY

4

INCOMPATIBLE_TYPES

Are you trying to add a number to a string?

5

TARGET_NOT_CALLABLE

Are you trying to invoke foo(), but foo = 123?

6

UNBOUND_LOCAL

Are you trying to use a variable before you put something in it?

7

BAD_GLOBAL_INDEX

8

EXCEEDED_MAX_BLOCK_STACK

Are you calling a function recursively to too great a depth, or having too many nested layers of function calls?

9

EXCEEDED_MAX_FRAME_STACK

10

EXCEEDED_MAX_OBJ_STACK

11

INVALID_FUNC_ARGS

Are you passing the wrong type of parameters to a function? Are you passing the wrong quantity of parameters?

12

UNSUBSCRIPTABLE_OBJECT

Are you trying to slice or index something other than a string, tuple, or byte list?

13

INVALID_SUBSCRIPT

Are you trying to access str[3] when str = ‘ABC’? (When str = ‘ABC’, str[0] is ‘A’, str[1] is ‘B’, and str[2] is ‘C’.)

14

EXCEEDED_MAX_LOCAL_STACK

Do you have too many local variables? Have you passed a large number of variables to nested levels of function calls?

15

BAD_CONST_INDEX

16

ALLOC_REF_UNDERFLOW

Do you have more than 255 variables referencing the same buffer, such as a single string buffer? If so, as SNAP creates references to them with its one-byte reference counter, it will wrap past zero (causing an ALLOC_REF_OVERFLOW error), and as it releases references to them, it will wrap down past zero generating this error. (Debug builds only.)

17

ALLOC_REF_OVERFLOW

Do you have more than 255 variables referencing the same buffer, such as a single string buffer? If so, as SNAP creates references to them with its one-byte reference counter, it will wrap past zero, generating this error, and as it releases references to them, it will wrap down past zero (generating an ALLOC_REF_UNDERFLOW error.) (Debug builds only.)

18

ALLOC_FAIL

Are you trying to keep too many string results? As of version 2.2, you are no longer limited to a single buffer for each type of string operation, but they are still limited in number.

19

UNSUPPORTED_TYPE

Have you tried to save an unsupported type, such as a tuple or iterator, to an NV parameter, or are you trying to pass an unsupported type (tuple, iterator, or byte list) in a SNAP packet?

20

MAX_PACKET_SIZE_EXCEEDED

Are you passing too large of a string value?

21

MAX_STRING_SIZE_EXCEEDED

Have you created a dynamic string too large for your platform?

22

EXCEEDED_C_DATA_SIZE

Your C code is trying to use more space for data than the firmware allows. Normally, this would be caught at compile time. However, if you get this error, the SNAP firmware has ignored your script and will not run it to prevent it from causing problems. To fix this, build your script using the firmware version currently running on the node.

23

INVALID_C_METADATA

The C code in the provided script was not compiled for the firmware image currently running. If you get this error, the SNAP firmware has ignored your script and will not run it to prevent it from causing problems. To fix this, build your script using the firmware version currently running on the node.

Note

If you are including C code in your SNAPpy script, your C code can use the pyerr macro to return one-byte error codes of your own definition. You can also use this as a way to return a second value from your C functions.

flowControl

flowControl(uart, isEnabled, isTxEnable)

Allows you to enable/disable flow control. Without flow control, there is a greater chance that characters will be dropped during communication; however, disabling flow control frees up two more pins (per UART) for use as other I/O. The initial state of flow control is set by bits 0x0080 (UART 1) and 0x0020 (UART 0) in NV11 - Feature Bits. By default, flow control is enabled. However, SNAP serial communications between nodes make no use of flow control.

When flow control is enabled, the SNAP node monitors the RTS pin from the attached serial device. As long as the SNAP node sees the RTS pin low, the node will continue sending characters to the attached serial device (assuming it has any characters to send). If the SNAP node sees the RTS pin go high, then it will stop sending characters to the attached serial device. By default, the SNAP node uses the CTS pin as a Clear To Send indication when flow control is enabled. The CTS pin indicates whether the SNAP node can accept more data. The CTS pin goes low if the SNAP node can accept more characters. The CTS pin goes high (temporarily) if the SNAP node is “full” and cannot accept any more characters. (The connected serial device can keep sending characters, but they will likely be dropped.)

It is important to realize that UART handshake lines are active-low. A low voltage level on the CTS pin is a boolean False but actually means that it is “Clear To Send.” A high voltage level on the CTS pins is a boolean True but actually means it is not “Clear To Send.” RTS behaves similarly.

The CTS pin can optionally act as a Transmit Enable (TXENA) indication using the isTxEnable parameter. In this mode, the CTS pin is normally high and transitions low before any characters are transmitted, remaining low until they have been completely sent.

When flow control is disabled, both the RTS and CTS pins are ignored.

Parameters
  • uartNum (int) – Specifies the UART (0 or 1).

  • isEnabled (bool) – Enables/disables hardware flow control.

  • isTxEnable (Optional[bool]) – Controls CTS behavior when flow control is enabled. If True, CTS acts as a TXENA pin. If False, CTS acts as Clear To Send. (Default is False.)

Returns

None

Note

Remember that some SNAP nodes may have only one UART available. The RF266, based on the AT128RFA1, has two UARTS, but only UART1 comes out to pins on the module.

getChannel

getChannel()

Get the SNAP channel (0-15) for SNAP devices operating in the 2.4 GHz range, which corresponds to the 802.15.4 channel.

Returns

SNAP channel that the node is currently on.

Return type

int

Possible return values are:

SNAP Channel

802.15.4 Channel

0

11

1

12

2

13

3

14

4

15

5

16

6

17

7

18

8

19

9

20

10

21

11

22

12

23

13

24

14

25

15

26

getEnergy

getEnergy()

Returns a number indicating the result of a brief radio Energy Detection scan on the currently selected channel, providing an indication of the noise floor for radio energy at that frequency.

Returns

Energy detected on the current channel in (-) dBm.

Return type

int

See also

getI2cResult

getI2cResult()

Returns the status code from most recent I2C operation, clearing the value in the process.

Returns

Result of the most recently attempted I2C operation.

Return type

int

The possible return values are:

Value

Enumeration

Meaning

0

I2C_OFF

I2C was never initialized

1

I2C_SUCCESS

The most recent I2C operation succeeded

2

I2C_BUS_BUSY

I2C bus was in use by some other device

3

I2C_BUS_LOST

Some other device stole the I2C bus

4

I2C_BUS_STUCK

There is a hardware or configuration problem

5

I2C_NO_ACK

The slave device did not respond properly

Note

This function can only be used after function i2cInit() has been called.

See also

  • User Guide on I2C

getInfo

getInfo(whichInfo)

Provides information about the RPC command currently being processed.

Parameters

whichInfo (int) –

Specifies the type of information to be retrieved.

Value

Information Returned

0

Vendor

1

Radio

2

CPU

3

Module Family

4

Build

5

Version (Major)

6

Version (Minor)

7

Version (Build)

8

Encryption

9

RPC Packet Buffer

10

Is Multicast

11

Remaining TTL

12

Remaining Small Strings

13

Remaining Medium Strings

14

Route Table Size

15

Routes in Route Table

16

Bank Free Space

17

Reserved

18

STDIN Hook Trigger

19

Remaining Tiny Strings

20

Remaining Large Strings

21

Script First Run

22

Script Base Address

23

Script Base Bank

24

Is Directed Multicast

25

Read and Reset Delay Factor (Directed Multicast Only)

26

Address Index (Directed Multicast Only)

27

Multicast Groups (Multicast & Directed Multicast Only)

28

Original TTL (Directed Multicast Only)

29

C Compiler ID

30

Build ID

Returns

Varies based on the value of whichInfo.

Return type

int

Vendor

Indicates the manufacturer of the radio module on which SNAP is running. Possible return values for getInfo(0):

Value

Manufacturer

0

Synapse

2

Freescale

3

CEL

4

ATMEL

5

Silicon Labs

7

PC

9

STMicrosystems

Radio

Indicates the method the node uses to connect to the rest of the network. Possible return values for getInfo(1):

Value

Method

0

802.15.4-based 2.4 GHz

1

None (Serial only)

3

868 MHz

4

Powerline

5

900 MHz Frequency-Hopping

6

802.15.4-based 900 MHz

CPU

Indicates the processor paired with the radio in the SNAP module. Possible return values for getInfo(2):

Value

Processor

0

Freescale MC9S08GT60A

1

ZIC 8051

2

MC9S08QE

3

Coldfire

4

ARM7

5

ATmega

6

Si100x 8051

7

X86

8

UNKNOWN

10

ARM CORTEX M3

Module Family

Indicates the module family. Possible return values for getInfo(3):

Value

Module Family

0

Synapse RF100 SNAP Engine

3

CEL ZIC2410

5

MC1321x

6

ATmega128RFA1

7

SNAPcom

8

Si100x

9

MC1322x

11

Si100x KADEX

13

Synapse RF300 SNAP Engine

14

Synapse RF200 SNAP Engine or SNAPstick 200

15

Synapse SM300 Surface Mount Module

16

Synapse SM301 Surface Mount Module

17

Synapse SM200 Surface Mount Module

19

Synapse RF266

20

STM32W108xB

27

Synapse SM220 Surface Mount Module, RF220UF1 SNAP Engine, or SNAPstick 220

30

Synapse RF220SU SNAP Engine

31

Synapse RF220SU-EU SNAP Engine

Build

Indicates whether the firmware in your SNAP module is a debug or release build. Possible return values for getInfo(4):

Value

Type

Trade-offs

0

debug

More error checking, slower speed, less SNAPpy room

1

release

Less error checking, faster speed, more SNAPpy room

Version

Indicates the Major, Minor and Build components of the firmware version. By using getInfo(5), getInfo(6), and getInfo(7), you can retrieve all three digits of the firmware version number.

Encryption

Indicates the type of encryption that is available in the module; however, it does not indicate what encryption (if any) is enabled for the module. Possible return values for getInfo(8):

Value

Encryption Support

0

Deprecated

1

AES-128

2

Basic encryption

RPC Packet Buffer

After you make an RPC call, a call to getInfo(9) returns an integer indicator of the packet buffer number used for the RPC call. That integer can be used in a function hooked to the HOOK_RPC_SENT event to determine that the processing of the packet buffer is complete. See the HOOK_RPC_SENT details for more information.

Is Multicast

Indicates how the RPC command currently being processed was invoked. Possible return values for getInfo(10):

Value

Meaning

0

Received via an addressed RPC command or was triggered by a system hook

1

Received via a multicast or directed multicast

Remaining TTL

Indicates how many “hops” the RPC command currently being processed had left before its end-of-life. You can use this information to tune your TTL values for your network to reduce broadcast chatter. This value is valid for both multicasts and directed multicasts, but not for addressed RPC commands.

Remaining Small Strings

Indicates how many “small” string buffers remain unused in your node. The size and number of small strings available on your node will vary depending on the underlying hardware and firmware.

Remaining Medium Strings

Indicates how many “medium” string buffers remain unused in your node. The size and number of medium strings available on your node will vary depending on the underlying hardware and firmware.

See also

Refer to SNAP Modules

Route Table Size

Indicates how many other nodes your node can keep track of in its address book. When a node needs to talk to another node, it must ask where that node is. It will find one of three things: that it can talk to the node directly, that it must communicate through another node, or that it cannot find the node at all. In these first two cases, SNAPpy keeps track of the path used to contact the node in a route table, so the next time it talks to the same node it does not have to query how to find the node first. How long the path to a node is kept depends on the mesh routing timeouts defined in the following NV parameters:

See also

User Guide on Preserving Unicast Routes

Routes in Route Table

Indicates how many of the routes in the node’s route table are in use, meaning how many other nodes the current node knows how to access without having to first perform a route request.

Bank Free Space

This query is only supported on platforms that support OTA Firmware Upload (it returns a value of 0 on the other platforms). This is how Portal knows if a given firmware image (.sfi file) will “fit” into the node.

STDIN Hook Trigger

Indicates what kind of data input event occurred that would have triggered HOOK_STDIN. Possible return values for getInfo(18):

Value

Meaning

0

In line mode, an end-of-line character (either \x0a or \x0d) was received, so the receive buffer contains a complete data transmission (less the EOL character, which is truncated) from the data source.

1

In line mode, the receive buffer received more data than it could hold, so the data received is not (necessarily) a complete transmission from the data source.

2

In character mode, the receive buffer received one character (or, depending on the incoming data rate, possibly more than one character).

See the stdinMode() function definition for a clarification of the difference between line mode and character mode.

Warning

Calling getInfo(18) from someplace other than a function hooked to HOOK_STDIN provides an undefined return value.

Remaining Tiny Strings

New in version SNAP 2.6.

Indicates how many “tiny” string buffers remain unused in your node. The size and number of tiny strings available on your node will vary depending on the underlying hardware and firmware.

Remaining Large Strings

New in version SNAP 2.6.

Indicates how many “large” string buffers remain unused in your node. The size and number of large strings available on your node will vary depending on the underlying hardware and firmware.

Script First Run

New in version SNAP 2.6.

Indicates whether the node has been rebooted since the last time a script was loaded onto it. Possible return values for getInfo(21):

Value

Meaning

0

There is no script on the node (either because it was empty when booted or because the script has been erased), or the node was rebooted since the script was loaded onto it.

1

The script has not been rebooted since the script was loaded onto it.

Script Base Address

New in version SNAP 2.6.

Indicates the base address for where the script resides in Flash.

Script Base Bank

New in version SNAP 2.6.

Indicates the base bank (zero-based) for where the script resides in Flash. For example, ATmega128RFA1’s Flash has two banks of 64K each and the SNAPpy script, by default, is located in the lower 64K bank. Therefore, getInfo(23) will return zero when called.

Is Directed Multicast

New in version SNAP 2.6.

Similar to getInfo(10), this indicates how the RPC command currently being processed was invoked and distinguishes between multicast and directed multicast. Possible return values for getInfo(24):

Value

Meaning

0

Received via an addressed RPC command, a multicast command, or was triggered by a system hook

1

Received via a directed multicast

Read and Reset Delay Factor

New in version SNAP 2.6.

Indicates the staggered delay (in milliseconds) that should be applied before targeted nodes make any reply to the directed multicast, giving nodes an opportunity to respond in sequence, without interfering with each other’s communications. See the description of the delayFactor parameter in the dmcastRpc() description for more information.

Invoking getInfo(25) clears the value, but also removes the staggered delay, putting the responsibility for avoiding communication collisions back in your hands. (There would be little reason to check this value without an intent to implement your own scheme to control communication timing.)

Warning

If called outside the context of a directed multicast, the return value is undefined.

Address Index

New in version SNAP 2.6.

Directed multicasts can target zero or more individual nodes by concatenating multiple addresses into the dstAddrs parameter. This indicates the (zero-based) position of this node’s address in a directed multicast address list.

Warning

The value is only meaningful in the context of a directed multicast call that specifically targets multiple nodes. In any other context (an addressed RPC, a regular multicast, or a directed multicast with an empty string for the target list) the return value is undefined.

Multicast Groups

New in version SNAP 2.6.

Indicates the multicast group mask specified for the call to the function being run. This is valid for both multicasts and directed multicasts. If the function is invoked with an addressed RPC call, this will return zero.

See mcastRpc() for more information about multicast groups.

Original TTL

New in version SNAP 2.6.

Indicates the value set for the ttl parameter on the dmcastRpc() call that invoked the running function. Note that this value is different from the Remaining TTL value, which provides the TTL remaining when the receiving node gets the message.

Warning

If called outside the context of a directed multicast, the return value is undefined.

C Compiler ID

New in version SNAP 2.7.

Indicates a unique identifier for the compiler version used to create any C code that has been compiled into the current SNAPpy script image. This has little practical value for the user at runtime, but it may be valuable in troubleshooting failures in scripts that include C code.

Build ID

New in version SNAP 2.7.

Indicates a unique identifier for the firmware build in your node, combining the firmware compilation date, Module Family, Build, Version (major, minor, and build), and Encryption into one hashed value. This has little practical value for the user at runtime, but it is used by SNAP to ensure that a script containing compiled C code was appropriately created for the firmware on which it is being asked to run.

getLq

getLq()

Get the most recent link quality (received signal strength) of the most recently received packet, regardless of which node that packet came from. Remember that the last packet could have come from a node that is close by or one that is far away.

Returns

A number in the range 0-127 (theoretical), representing the link quality in (-) dBm.

Return type

int

Note

Because this value represents (-) dBm, lower values represent stronger signals, and higher values represent weaker signals.

getMs

getMs()

Get the value of a free-running counter within the SNAP Engine representing elapsed milliseconds since startup. Since the counter is only 16 bits, it rolls over every 65.536 seconds. Because all SNAPpy integers are signed, the counter’s full cycle is:

0, 1, 2, ..., 32766, 32767, -32768, -32767, -32766, ..., -3, -2, -1, 0, 1, ...

Some scripts use this function to measure elapsed (relative) times. The value for this function is only updated between script invocations (events), meaning that you will get the same value no matter how many times you call getMs() during the same event.

Returns

16 bit count of milliseconds since startup.

Return type

int

getNetId

getNetId()

Get the current Network Identifier (ID).

The node will only accept packets containing this ID, or a special wildcard value of 0xffff which is used during the “find nodes” process.

The Network ID and the Channel are what determine which radios can communicate with each other in a wireless network. Radios must be set to the same Channel and Network ID in order to communicate over the air. Nodes communicating over a serial link pay no attention to the Channel and Network ID.

Returns

The node’s current Network ID.

Return type

int

See also

getStat

getStat(whichStat)

This function returns details about how busy the node has been with processing packets. Each return value ranges from 0 to 255. The values “peg” at 255 (i.e., once reaching 255 they stay there until cleared). Reading a value resets the counter to 0.

Parameters

whichStat (int) –

Specifies the counter to be retrieved.

Value

Counter Name

What is being counted?

0

Null Transmit Buffers

Buffers transmitted via a null serial port

1

UART0 Receive Buffers

Buffers received via UART0

2

UART0 Transmit Buffers

Buffers transmitted via UART0

3

UART1 Receive Buffers

Buffers received via UART1

4

UART1 Transmit Buffers

Buffers transmitted via UART1

5

Transparent Receive Buffers

Buffers received via transparent serial mode

6

Transparent Transmit Buffers

Buffers transmitted via transparent serial mode

7

Packet Serial Receive Buffers

Buffers received via packet serial mode

8

Packet Serial Transmit Buffers

Buffers transmitted via packet serial mode

9

Radio Receive Buffers

Buffers received via the radio

10

Radio Transmit Buffers

Buffers transmitted via the radio

11

Radio Forwarded Unicasts

Unicasts forwarded to nodes via the radio

12

Packet Serial Forwarded Unicasts

Unicasts forwarded to nodes via packet serial

13

Radio Forwarded Multicasts

Multicasts forwarded to nodes via the radio

14

Packet Serial Forwarded Multicasts

Multicasts forwarded to nodes via packet serial

Returns

Varies based on the value of whichStat.

Return type

int

i2cInit

i2cInit(enablePullups, SCL_pin, SDA_pin)

Performs the necessary setup for the I2C bus, including enabling internal pull-up resistors and optionally re-assigning the SCL and SDA I2C pins to another pair of SNAPpy IO pins.

The I2C clock and data lines require pull-ups. You can either choose to use your own external hardware or rely on the built-in internal ones. The internal pull-up resistors can come in handy when you are doing quick prototyping by dangling I2C devices directly off the SNAP Engine.

Parameters
  • enablePullups (bool) – Internal pull-up resistors are enabled when True; disabled when False.

  • SCL_pin (Optional[int]) – Specifies which SNAPpy IO pin to be used for SCL.

  • SDA_pin (Optional[int]) – Specifies which SNAPpy IO pin to be used for SDA.

Returns

None

Warning

Be careful not to “double pull-up” the I2C bus!

See also

i2cRead

i2cRead(byteStr, numToRead, retries, ignoreFirstAck)

Since I2C devices must be addressed before data can be read out of them, this function performs a write followed by a read.

Parameters
  • byteStr (str) – Specifies whatever “addressing” bytes must be sent to the device to get it to respond.

  • numToRead (int) – Specifies how many bytes to read back from the external I2C device.

  • retries (int) – Controls a spin-lock count used to give slow devices extra time to respond. Try an initial value of 1 and increase if needed.

  • ignoreFirstAck (bool) – True for devices that do not send an initial “ack” response, which will prevent an I2C error based on lack of an initial acknowledgement; False otherwise.

Returns

Bytes read from the external I2C device.

Return type

str

Note

This function can only be used after function i2cInit() has been called.

See also

  • User Guide on I2C

i2cWrite

i2cWrite(byteStr, retries, ignoreFirstAck, endWithRestart=False)

Writes a byte string to the I2C bus.

Parameters
  • byteStr (str) – Specifies the data to be sent to the external I2C device, including whatever “addressing” bytes must be sent to the device to get it to pay attention.

  • retries (int) – Controls a spin-lock count used to give slow devices extra time to respond. Try an initial value of 1 and increase if needed.

  • ignoreFirstAck (bool) – True for devices that do not send an initial “ack” response, which will prevent an I2C error based on lack of an initial acknowledgement; False otherwise.

  • endWithRestart (Optional[bool]) – True for devices that expect an I2C restart between I2C commands; False for devices that expect an I2C Start - Stop handshake sequence. Default is False. This argument was added in SNAP 2.5.

Returns

Number of bytes actually written.

Return type

int

Note

This function can only be used after function i2cInit() has been called.

See also

  • User Guide on I2C

imageName

imageName()

A SNAPpy script (.py file) gets compiled into a byte-code SNAPpy image (.spy file) using either SNAPbuild or Portal. The SNAPpy image name is assigned during this process from the underlying SNAPpy script. For example, image foo.spy would be generated from a script named foo.py. In this case, imageName() would return the string foo, even if someone had renamed the foo.spy file to a different name before loading it.

Returns

Name of currently loaded SNAPpy image.

Return type

str

Note

This returns the SNAPpy image that gets downloaded into the node, not the original (textual) source code.

initUart

initUart(uart, bps, dataBits=8, parity='N', stopBits=1)

Programs the specified UART to the specified bits per second (bps), or baud rate. Optionally, the data bits, parity, and stop bits can also be set.

Flow control defaults to the setting specified in NV11 - Feature Bits, typically it’s ‘On’. Use the flowControl() function to specify a setting.

Parameters
  • uartNum (int) – The specified UART, 0 or 1.

  • bps (int) – Usually set to the desired bits per second (1200, 2400, 9600, etc.); however, a value of 1 selects 115,200 bps (this large number would not fit into a SNAPpy integer and was treated as a special case). A value of 0 disables the UART.

  • dataBits (Optional[int]) – 7 or 8. (Default is 8.)

  • parity (Optional[str]) – ‘E’, ‘O’ or ‘N’, representing EVEN, ODD, or NO parity. (Default is ‘N’.)

  • stopBits (Optional[int]) – Number of stop bits. (Default is 1.)

Returns

None

Note

You are not limited to “standard” baud rates. If you need 1234 bps, you are allowed to do that.

initVm

initVm()

Calling this function restarts the SNAPpy virtual machine. It will clear all globals you may have changed in your SNAPpy code back to their initially declared values, and it will cause all static or global variables declared in C code in SNAP 2.7 or newer to be reinitialized. It does not, however, reinvoke the SNAPpy script’s “startup” handler (the function hooked to the HOOK_START event).

This function is normally only used by Portal and SNAPconnect at the end of the script upload process.

Returns

None

int

int(obj)

Converts the specified object (usually a string) into numeric form.

Parameters

obj – Object to transform into a number.

Returns

Numeric representation of obj.

Return type

int

Examples

int('123')      # Returns 123
int(True)   # Returns 1
int(False)  # Returns 0

Note

Unlike regular Python, the SNAPpy int() function does not take an optional second parameter indicating the numeric base to be used. The obj to be converted to a numeric value is required to be in base 10 (decimal).

len

len(sequence)

This function returns the size of parameter sequence. This will be an element count for a tuple or the number of characters in a string.

Parameters

sequence – Must be a string or a tuple.

Returns

Number of items in sequence.

Return type

int

Examples

len('ABC') # Returns 3

loadNvParam

loadNvParam(id)

This function reads a single parameter from the SNAP node’s NV storage and returns it to the caller. For a full list of all the system (reserved) id values, refer to section 3. User parameters should have id values in the range 128-254.

Parameters

id (int) – Specifies which NV parameter to read.

Returns

Depends on the NV parameter.

See also

localAddr

localAddr()

Get the node’s local network address on the SNAP network.

Tracking what is essentially a six-digit (hexadecimal) number as a three-character string means that representations of the SNAP address may not appear meaningful when displayed. For example, if you were to use Portal to invoke localAddr() on a node with a a SNAP address of 5D.E3.AB, Portal’s Event Log would display the return value as ]ã«. If you were to display ord("]") or ord(localAddr()[0]) you would get 93, which is the decimal equivalent of hex 0x5D. Similarly, ord("ã") yields 227, which is the decimal equivalent of 0xE3, and ord("«") yields 171, which is the decimal equivalent of 0xAB. You could build this string directly as \x5d\xe3\xab.

This string representation of numbers as their separate character strings is a fundamental part of specifying addresses of nodes for SNAP communications.

Returns

String representation of the node’s 3-byte address on the SNAP network.

Return type

str

mcastRpc

mcastRpc(dstGroups, ttl, remoteFunction, *remoteFunctionArgs)

Make a remote procedure call (RPC) using multicast messaging, meaning this message could be acted upon by multiple SNAP nodes.

Parameters
  • dstGroups (str) – Specifies which nodes should respond to the request.

  • ttl (int) – Specifies the Time To Live (TTL) for the request, which is basically how many hops the message is allowed to make before being discarded.

  • remoteFunction (str) – Specifies which function to invoke on the remote node.

  • *remoteFunctionArgs (arbitrary argument list) – Used if the remote function takes any parameters.

Returns

This function normally returns True; however, it does not mean your RPC request was successfully sent and received.

It returns False only if it was unable to attempt the Remote Procedure Call (for example, if the node is low on memory or the RPC was too large to send).

Return type

bool

See also

mcastSerial

mcastSerial(dstGroups, ttl)

Set serial transparent mode to multicast.

Parameters
  • dstGroups (int) – Specifies the multicast groups that are eligible to receive this data.

  • ttl (int) – Specifies the maximum number of hops the data will be re-transmitted.

Returns

None

Warning

Multicast serial transparent mode is less reliable than unicast serial transparent mode, because the received serial characters will be sent using unacknowledged multicast messages.

See also

monitorPin

monitorPin(pin, isMonitored)

Enable background monitoring of a digital input pin’s level.

When a SNAPpy IO pin changes state, a HOOK_GPIN event is sent to the SNAPpy virtual machine. If you have assigned a HOOK_GPIN handler, it will be invoked with the number of the SNAPpy IO pin that changed state and the pin’s new value.

Parameters
  • pin (int) – Specifies which SNAPpy IO pin to monitor.

  • isMonitored (bool) – Enables monitoring when True, and disables monitoring when False.

Returns

None

Note

This SNAPpy IO pin must first be configured as a digital input pin using setPinDir().

See also

ord

ord(str)

Given a one-character string, this returns an integer of the ASCII for that character.

Parameters

str (str) – Specifies a single-character string to be converted.

Returns

Integer value of the ASCII character str.

Return type

int

Examples

::

The result of ord(‘A’) is 65 (0x41). The result of ord(‘2’) is 50 (0x32).

peek

peek(addr)

Read a byte from a specific memory location.

Parameters

addr (int) – Specifies which memory location to read (0-0x7FFF). A negative address will read a byte from internal EEPROM (-1 to -4096)

Returns

This returns the memory contents of the specified memory address

Return type

int

See also

  • poke() for writing the contents of a specific memory address

poke

poke(addr, byteVal)

Write the value of a specific memory location.

Parameters
  • addr (int) – Specifies which memory location to write (0-0x7FFF). A negative address will write a byte to internal EEPROM (-1 to -4096)

  • byteVal (int) – Specifies the data value which will be written to the specified memory address

Returns

None

See also

  • peek() for reading the contents of a specific memory address

pulsePin

pulsePin(pin, msWidth, isPositive)

Apply a pulse with a specified duration to a digital output pin.

The pulsePin() function behaves differently based on the value of msWidth:

  • Specifying a positive value for msWidth will generate a non-blocking pulse, meaning your SNAPpy script continues to run in parallel. This also allows you to have multiple pulses in progress at the same time. In this case, msWidth specifies the desired pulse width in milliseconds (1-32767).

  • Specifying a negative value for msWidth makes the pulse generation blocking, meaning the pulse runs to completion, and then your SNAPpy script resumes execution at the next line of code. In this case, the value of msWidth is platform-specific, but the desired pulse width is typically in microseconds. As a quick example, a value of -10000 on a Synapse RF200 would result in a pulse that is 10 milliseconds wide.

If you have multiple pulses on the same pin with the same isPositive setting, the first pulse to complete will set the pin to its final state, and the second pulse to complete will effectively have ended.

Parameters
  • pin (int) – Specifies which SNAPpy IO pin to pulse.

  • msWidth (int) – Specifies the desired pulse width and determines if the function will return immediately or wait until the pulse is complete. Specifying a value of 0 will result in no pulse at all.

  • isPositive (bool) – Controls the polarity of the pulse.

Returns

None

Note

This SNAPpy IO pin must first be configured as a digital output pin using setPinDir().

Warning

The timing of the pulsePin() function is not guaranteed to be precise. Pulses begin when the function invokes and end at a tick of the node’s internal clock. If you were to initiate a 1 ms pulse very shortly before the node’s next millisecond tick, the pulse would would be notably shorter than the 1 ms specified.

See also

random

random()

Returns a pseudo-random number.

Returns

A number between 0-4095.

Return type

int

readAdc

readAdc(channel)

Sample ADC on the specified analog input channel.

Some channels correspond to external analog input pins, the internal low voltage reference, or the internal high voltage reference. On some platforms, these can also return specialty readings such as processor temperature or voltage differences.

Parameters

channel (int) – Specifies which analog input channel to read.

Returns

Value of the specified analog input channel.

Return type

int

See also

readPin

readPin(pin)

Reads the current level of either a digital input or digital output pin.

Parameters

pin (int) – Specifies which SNAPpy IO pin to read.

Returns

The current logic level of the specified pin. It returns a “live value” for an input pin or the last value written for an output pin.

Return type

bool

Note

This SNAPpy IO pin must first be configured as a digital input or output pin using setPinDir().

See also

reboot

reboot(delay=200)

Reboot the node after an optional delay.

Providing for a delay allows the node time to acknowledge the reboot() request (in case it came in over-the-air). The delay parameter is treated as an unsigned integer. Sending 0xEA60 provides 60,000 ms, or one minute, of delay, as negative values (-5,536 in this case) are not meaningful.

The delay parameter is available beginning in SNAP 2.6.

Parameters

delay (Optional[int]) – Specifies when the reboot is to occur, in milliseconds. (Default is 200.) New in SNAP 2.6.

Returns

None

Note

Once a reboot is issued, scheduling a reboot later than an already running countdown will have no effect. However, issuing a reboot with a shorter duration than the current countdown will work.

resetVm

resetVm()

Reset the SNAPpy virtual machine ,which halts the currently running script. Even though the script is halted, it remains loaded in the node.

Returns

None

Note

Synapse tools like Portal and SNAPconnect use this in the script upload process.

See also

rpc

rpc(nodeAddress, remoteFunction, *remoteFunctionArgs)

Request that another SNAP node execute a function.

Parameters
  • nodeAddress (str) – Specifies the SNAP address of the target node.

  • remoteFunction (str) – Specifies which function to invoke on the remote node.

  • *remoteFunctionArgs (arbitrary argument list) – Used if the remote function takes any parameters.

Returns

This function normally returns True; however, it does not mean your RPC request was successfully sent and received.

It returns False only if it was unable to attempt the Remote Procedure Call (for example, if the node is low on memory or the RPC was too large to send).

Return type

bool

See also

rpcSourceAddr

rpcSourceAddr()

If a function on a node is invoked remotely (via RPC), then the called function can invoke function rpcSourceAddr() to find out the network address of the node which initiated the call. (If you call this function when an RPC is not in progress, it just returns None.)

This function allows a node to respond (answer back) directly to other nodes. An example will make this clearer. Imagine node “A” is loaded with a script containing the following function definition:

def pong():
    print 'got a response!'

Now imagine node “B” is loaded with a script containing the following function:

def ping():
    rpc(rpcSourceAddr(),'pong')

Node A can invoke function “ping” on node B. It can do this with a direct RPC, but it has to know node B’s address to do so:

rpc(node_B_address_goes_here, 'ping')

Or, it can do it with a multicast RPC, assuming that node B’s group membership is set appropriately:

mcastRpc(1, 1, 'ping')

When node B receives the RPC request packet, it will invoke local function “ping”, which will generate the remote “pong” request. Notice that node B can respond to a “ping” request from any node.

All SNAP network addresses are three-byte strings. Please see the localAddr() function for a description of how SNAP addresses are specified and notated.

Returns:

See also

rx

rx(isEnabled)

This function allows you to power down the radio, extending battery life in applications that do not actually need the radio (or only need it intermittently).

The radio defaults to ON in SNAP nodes. If you invoke rx(False), the radio will be powered down. Invoking rx(True), or sending any data over the radio, will power the radio back up.

To be clear, a node can wake up its own radio by attempting to transmit. A node’s radio will not be woken up by transmissions from other nodes.

Parameters

isEnabled (bool) – Controls whether or not the radio is on.

Returns

None

Note

If you turn the radio off (using rx(False)), then you will not receive any more radio traffic!

saveNvParam

saveNvParam(id, obj, bitmask)

Save object to indexed non-volatile storage location.

Parameters
  • id (int) – Specifies which NV parameter to modify.

  • obj – The data to be saved. Depending on the NV parameter, the data type could be boolean, integer, string, byte list, or None.

  • bitmask (Optional [int]) – Specifies which bits in obj will update the NV parameter’s value. Omitting this argument will overwrite the previous value with obj. This argument should only be used with integer obj values. New in version SNAP 2.6.

Returns

A result code.

Return type

int

The possible return values are:

Value

Enumeration

0

NV_SUCCESS

1

NV_NOT_FOUND

2

NV_DEST_TOO_SMALL

3

NV_FULL

4

NV_BAD_LENGTH

5

NV_FAILURE

6

NV_BAD_TYPE

7

NV_LOW_POWER

Examples

Assume that NV11 - Feature Bits contains the value 0x001F, which indicates that there is a power amplifier and that both UARTs are enabled. The following command will enable the Packet CRC bit (0x0400):

saveNvParam(NV_FEATURE_BITS_ID, 0x0400)         # NV11 = 0x0400

However, it will also overwrite all the other feature bits, disabling the power amplifier and both UARTs in the process. Instead, you need to combine the bit values:

saveNvParam(NV_FEATURE_BITS_ID, 0x041F)         # NV11 = 0x041F

Beginning in SNAP 2.6, you can use the optional bitmask argument:

saveNvParam(NV_FEATURE_BITS_ID, 0x0400, 0x0400) # NV11 = 0x041F

Note

NV parameters 128-254 are user-defined, so your script can use these parameters however you want. All values except None consume flash space. If you plan to no longer use a user-defined NV parameter, setting it to None will regain the flash space.

See also

scanEnergy

scanEnergy()

The getEnergy() function returns the result of a brief radio energy detection scan, as an integer. Function scanEnergy() is an extension of getEnergy(). It essentially calls getEnergy() N times in a row, changing the frequency before each getEnergy() scan. Here, ‘N’ refers to the number of frequencies supported by the radio.

For 2.4 GHz radios, 16 frequencies are supported by the radios, each corresponding to one channel. For 900 MHz radios running FHSS (frequency hopping) firmware, the 16 channels cover 66 radio frequencies, with each channel making use of 25 of those frequencies. For 868 MHz radios, there are three frequencies used, regardless of the channel selected. See the getChannel() function explanation for more details about how each radio platform uses the various frequencies available to it.

The scanEnergy() function returns an N-byte string, where the first character corresponds to the “detected energy level” on frequency 0, the next character corresponds to channel 1, and so on. (For 900 MHz FHSS radios, SNAP does not make use of the first and last frequencies but returns them as part of the string for completeness.) Thus, ord(scanEnergy()[4]) would return the same integer that calling getEnergy() from channel 4 would return.

The units for the “detected energy level” are the same as that returned by getLq(). Refer to the documentation on that function for more info.

Returns:

setChannel

setChannel(channel, network_id)

Set the SNAP Channel, and optionally the SNAP Network ID, of the node.

Parameters
  • channel (int) – Specify which frequency (or range of frequencies) the device should use for its communications. Values are platform specific.

  • network_id (Optional[int]) – Specify the SNAP Network ID (0-0xFFFF); if excluded, the node’s SNAP Network ID will be unchanged. New in version SNAP 2.6.

Returns

None

Example

setChannel(7 ,0x0C70)  # set the SNAP Channel to 7 and the SNAP Network ID to 0x0C70

Warning

This function only changes the “live” settings, so the effect lasts until the next reboot or power cycle. Use saveNvParam() to persist these settings into the correct NV Parameter.

Note

channel values 0-15 correspond to 802.15.4 channel 11-26 on 802.15.4/2.4 GHz devices.

setNetId

setNetId(netId)

Set the SNAP Network ID of the node.

The combination of network ID and channel are what determine which radios can communicate with each other in a wireless network. Radios must be set to the same channel and network ID in order to communicate over the air. (Of course, they also must be transmitting in the same frequency band. 900 MHz radios set to a given channel cannot communicate over the air with 2.4 GHz radios set to the same channel.) Nodes communicating over a serial link pay no attention to the channel and network ID.

Parameters

netId (int) – Specify the SNAP Network ID (0-0xFFFF).

Returns

None

Note

  • 0xFFFF is considered a “wildcard” network ID (matches all nodes), and you normally should only use network IDs of 0-0xFFFE.

  • This function changes the “live” network ID setting, and the effect only lasts until the next reboot or power cycle, or until setNetId() is called again. You should also use saveNvParam() to save the “persisted” network ID setting in NV3 - Network ID, if you want the node to stay on that network ID after its next reboot.

setPinDir

setPinDir(pin, isOutput)

Configures a SNAPpy IO pin as either a digital input or digital output.

Parameters
  • pin (int) – Specifies which SNAPpy IO pin to configure.

  • isOutput (bool) – Pin is output when True; input when False.

Returns

None

Note

  • Calling setPinDir with a pin that is in use by another peripheral (eg UART or ADC) will automatically disable it.

See also

setPinPullup

setPinPullup(pin, isEnabled)

Enables the internal pull-up resistor for an IO pin.

Parameters
  • pin (int) – Specifies which SNAPpy IO pin to configure.

  • isEnabled – Enables the SNAPpy IO pin’s internal pull-up when True; disables when False.

Returns

None

Note

  • A SNAPpy IO pin’s internal pull-up is disabled by default.

  • This SNAPpy IO pin must first be configured as a digital input pin using setPinDir().

See also

setPinSlew

setPinSlew(pin, isRateControl)

Enable slew rate-control (~30ns) for a digital output pin.

Parameters
  • pin (int) – Specifies which SNAPpy IO pin to configure.

  • isRateControl – Enables the SNAPpy IO pin’s slew rate-control when True; disables when False.

Returns

None

Note

  • A SNAPpy IO pin’s slew rate-control is disabled by default.

  • This SNAPpy IO pin must first be configured as a digital output pin using setPinDir().

See also

setRadioRate

setRadioRate(rate)

Set the data rate of the radio. Only nodes set to the same rate can talk to each other over the air! All radios on the same frequency range and set to rate 0 will be interoperable.

Parameters

rate (int) – 0 specifies the standard data rate for the platform. Other rate values are platform-specific.

Returns

None

Warning

The “encoding” for non-standard data rates may differ between radio manufacturers. This means that different radio hardware may not be interoperable, even if set to the same (non-standard) rate.

See also

setRate

setRate(rateNum)

Adjusts the background sampling rate of digital IO pins.

Parameters

rateNum (int) – Specifies the background sampling rate.

Returns

None

The possible values for rateNum:

Value

Rate

0

OFF

1

Every 100 ms

2

Every 10 ms

3

Every 1 ms

Note

  • The background sampling rate is every 100 milliseconds by default.

  • This function has no effect unless/until you are using the monitorPin() function.

See also

sleep

sleep(mode, ticks)

This function puts the radio and CPU on the SNAP node into a low-power mode for a specified number of ticks. This is used to extend battery life.

A ticks parameter of 0 can be used to sleep until an IO pin interrupt occurs (see script pinWakeup.py), but SNAPpy is smart enough to know if you have not enabled a wakeup pin and will ignore a sleep(mode, 0) if there is no wakeup possible. Note that on some platforms not all processor pins come out to module pins; it might be possible to specify a wake pin that is not accessible, thus locking your node into a sleeping state. If this happens, make a serial connection to the node and use Portal ‘s Erase SNAPpy Image… menu option to clear the script and start over.

Starting with version SNAP 2.2, a negative ticks parameter can be used to access alternate sleep timings.

Starting with version SNAP 2.4.24, for most platforms the sleep function returns the remaining number of ticks if the node has been woken by a pin interrupt rather than the sleep call timing out. If the complete timed sleep has occurred, or if the sleep was untimed, the function returns zero. For example if you were to invoke sleep(1, 60) on a node but woke the node with an interrupt after 20 seconds, the function would return 40.

Parameters
  • mode – Chooses from the available sleep modes. The number of modes available and their characteristics, such as resolution and accuracy, is platform-specific.

  • ticks

Returns:

See also

spiInit

spiInit(clockPolarity, clockPhase, isMsbFirst, isFourWire)

Initializes the Serial Peripheral Interface (SPI) Bus for the SNAP node.

Parameters
  • clockPolarity (bool) – Specifies the level of the CLK pin between SPI exchanges. True specifies that the clock is high when idle, and False specifies that the clock is low when idle.

  • clockPhase (bool) – Specifies which clock edge the incoming data will be latched in. If you number clock edges from 1, then True specifies the even clock edges for incoming data, and False specifies the odd clock edges for incoming data.

  • isMsbFirst (bool) – Controls the order in which individual bits within each byte will be shifted out. Setting this parameter to True will make the 0x80 bit go out first, and setting this parameter to False will make the 0x01 bit go out first.

  • isFourWire (bool) – Select the variant of SPI you are connecting to: True is four-wire, and False is three-wire.

Returns

None

Note

These settings depends on the device to which you are interfacing.

See also

spiRead

spiRead(byteCount, bitsInLastByte=8)

Reads data from a three-wire SPI device.

Parameters
  • byteCount (int) – Specifies how many bytes to read.

  • bitsInLastByte (int) – Makes it possible to accommodate devices with data widths that are not multiples of 8 bits. Value should be equal to the data width of device modulo 8. (Default is 8.)

Returns

Bytes received from SPI.

Return type

str

Note

This function can only be used after function spiInit() has been called.

See also

spiWrite

spiWrite(byteStr, bitsInLastByte=8)

Writes data to a three or four-wire SPI device.

Parameters
  • byteStr (str) – Specifies the actual bytes to be shifted out.

  • bitsInLastByte (int) – Makes it possible to accommodate devices with data widths that are not multiples of 8 bits. Value should be equal to the data width of device modulo 8. (Default is 8.)

Returns

None

Note

This function can only be used after function spiInit() has been called.

See also

  • User Guide on SPI

  • spiXfer() - to write and read data simultaneously (four-wire SPI only)

spiXfer

spiXfer(byteStr, bitsInLastByte=8)

Bidirectional data transfer over a four-wire SPI device. As bits are being shifted out to the slave device on the MOSI pin, bits from the slave device on the MISO pin are simultaneously being shifted in.

Parameters
  • byteStr (str) – Specifies the actual bytes to be shifted out.

  • bitsInLastByte (int) – Makes it possible to accommodate devices with data widths that are not multiples of 8 bits. Value should be equal to the data width of device modulo 8. (Default is 8.)

Returns

Byte string consisting of the bits that were shifted in (as the bits specified by parameter byteStr were

shifted out).

Return type

str

Note

This function can only be used after function spiInit() has been called.

See also

stdinMode

stdinMode(mode, echo)

This function controls whether or not received characters are echoed back to the user and how serial data is presented to your SNAPpy script via the HOOK_STDIN handler.

You can choose between line mode or character mode:

Line Mode

Characters are buffered up until either a Carriage Return (CR) or Line Feed (LF) is received. The complete string is then passed to your SNAPpy script via the HOOK_STDIN handler. Either the CR or LF character can trigger the hand-off, so if your terminal (or terminal emulator) is automatically adding extra CR or LF characters, you will see additional empty strings ("") passed to your script. For example, the character sequence A B C CR LF (or \x41\x42\x43\x0d\x0a) looks like two lines of input to SNAPpy.

Character Mode

Characters are passed to your SNAPpy script as soon as they become available via the HOOK_STDIN handler. If characters are being received fast enough, it still is possible for your script to receive more than one character at a time; they are just not buffered waiting for a CR or LF.

Parameters
  • mode (int) – 0 for line mode; 1 for character mode.

  • echo (bool) – True will retransmit any received characters to the sender.

Returns

None

Note

While your node is in line mode, SNAP reserves one “medium” string buffer to accept incoming data from STDIN. If your script is heavy on string usage but does not make use of HOOK_STDIN, you can recover use of the medium string used by line mode by changing to character mode.

See also

str

str(obj)

Given an element, returns a string representation of the element.

Parameters

obj – Element to be transformed into a string.

Returns

String representation of the element.

Return type

str

Examples

str(True)    # returns 'True'
str(123)     # returns '123'
str('hello') # returns 'hello'

txPwr

txPwr(power)

The radio on the SNAP node defaults to the maximum power allowed. Function txPwr() lets you reduce the power level from this default maximum.

Parameter power specifies a transmit power level from 0-17, with 0 being the lowest power setting and 17 being the highest power setting. On some platforms, government regulations prevent the hardware from being usable above certain levels. On one of those platforms, setting the transmit power higher than allowed pegs the power output at the highest allowed amount, so there may be no practical difference between setting the power to 16 and setting it to 17, for example.

Parameters

power (int) – The TX power level, in the range 0-17.

Returns

None

See also

type

type(arg)

Given a single argument, it returns an integer indicating the data type of the argument.

This function does not distinguish between constant or dynamic variables, nor between user functions or SNAPpy built-in functions.

Parameters

arg – Object to inspect.

Returns

Integer indicating the type of the object passed to it.

Return type

int

The expected return values (different from that returned in Python) are:

0

None

1

Integer

2

String

3

Function

5

Boolean

6

Tuple

7

Iterator

8

Byte List

31

Unknown

Note

Typically, you will not be able to create variables of an unknown type. However, if you have a Byte List variable and you use the del keyword to delete the entire list, the variable will be left with contents of an unknown type. Removing all elements from a list does not set the variable to an unknown type. Only deleting the list itself will do that.

ucastSerial

ucastSerial(dstAddr)

Set serial transparent mode to unicast.

Parameters

dstAddr – Specifies the SNAP address of the destination node.

Returns

None

See also

uniConnect

uniConnect(dst, src)

Establishes a one-way connection between two SNAP data-sources.

Parameters
  • dstSNAP data destination.

  • srcSNAP data source.

Returns

None

See also

vmStat

vmStat(statusCode, args)

This function is specialized for management applications like Portal and provides a range of control/callback functionality.

Parameters
  • statusCode (int) – Controls what actions will be taken and what data will be returned via tellVmStat().

  • args – Varies depending on the statusCode. See below for details.

Returns

This function does not return a value, but it causes a tellVmStat() call to be made to the node that requested the vmStat().

The currently supported statusCode values are:

0-3

RESERVED

Internal Use Only

4

VM_NVREAD

Read and return the specified NV parameter

5

VM_NAME

Returns NODE NAME if set, else IMAGE NAME, plus Link Quality

6

VM_VERSION

Returns software version number

7

VM_NET

Returns Network ID and Channel

8

VM_SPACE

Returns Total Image (script) Space Available

9

VM_SCAN

Scans all RF channels for energy

10

VM_INFO

Returns Image Name (script name) and Link Quality

11

VM_DATA_SPACE

Returns the amount of space available for a SNAPpy image in auxiliary memory (valid only for the Si1000-based SNAP modules RF300, RF301, SM300, SM301)

12

VM_TOPOLOGY

Returns a string providing a list of nodes with which the target node can directly communicate

After the “varying” args parameter comes a final optional argument that specifies a “reply window” (in seconds) to randomly reply within. This helps prevent communication interference if you send a vmStat() command to multiple nodes concurrently.

If you do not specify a “reply window” parameter (or specify zero), the nodes will respond as rapidly as they can (subject to network traffic, communication difficulties, etc.).

Some of these commands are multicast by Portal; the “reply window” provides a way to keep all of the nodes from trying to respond at once. Specifying a non-zero “reply window” tells the node to pick a random time within the next “reply window” seconds and wait until then to reply.

Return Value Format:

When a node receives a vmStat() call, it responds to the source node with a call to tellVmStat(word, data).

The least significant byte of word will be the originally requested statusCode. The most significant byte will vary depending on the statusCode and is the “hiByte” described below. The data value is the main return value and is also dependant on the statusCode. For example, if a vmStat(4, 15, 3) were called, the called node would, within 3 seconds, reply with tellVmStat(3844, {contents of NV parameter 15 on the node}). Note that the second parameter could be an integer, a string, a Boolean, or None.

The 3844 value that was returned as word equates to 0x0F04. The “hiByte” of this value, 0x0F, indicates which NV parameter was read. The “lowByte” of this value, 0x04, indicates that the returned value comes as a result of a VM_NVREAD call. If the value of the first returned parameter is greater than 10, the “lowByte” will always contain the calling code, while the significance of the “hiByte” will vary depending on what call was made.

VM_NVREAD

For VM_NVREAD, the args parameter is the ID of the NV parameter you want to read. (These are the same IDs used in the saveNvParam() and loadNvParam() functions. The “system” NV parameter IDs are given in section 3.) You can also optionally specify a “reply window.”

The reported values will be a “hiByte” of the NV parameter ID and a “data” of the actual NV parameter value.

VM_NAME

For VM_NAME, the only parameter is the optional reply window.

The reported “data” value will be a string name and a Link Quality reading.

VM_VERSION

For VM_VERSION, the only parameter is the optional reply window.

The reported “data” value will be a version number string.

VM_NET

For VM_NET, the only parameter is the optional reply window.

The reported values will be a “hiByte” containing the currently active channel, and a “data” value of the current Network ID.

VM_SPACE

For VM_SPACE, the only parameter is the optional reply window.

The reported “data” value will be the Total Image (script) Space Available.

VM_SCAN

For VM_SCAN, the only parameter is the optional reply window.

The reported “data” value will be a string containing the detected energy levels on all channels. This value is identical to the value returned by the scanEnergy() function. Note that each scan just represents one point in time. You will probably have to initiate multiple scans to determine which channels actually have SNAP nodes on them.

You can see this VM_SCAN function put to use in the Channel Analyzer feature of Portal.

VM_INFO

For VM_INFO, the only parameter is the optional reply window.

The reported values will be a “hiByte” of the current Link Quality and a “data” of the currently loaded script name (a string).

VM_DATA_SPACE

For VM_DATA_SPACE, the only parameter is the optional reply window.

The reported values will be a “hiByte” of the current Link Quality and a “data” of the space available in auxiliary memory for a SNAPpy script (an integer).

VM_TOPOLOGY

For VM_TOPOLOGY, the only parameter is the optional reply window.

The reported values will be a “hiByte” of the current Link Quality and a “data” of details about nodes with which the reporting node can directly communicate (a string). Each node with which the reporting node can directly communicate will be represented by a block of five characters: The first three will be the node’s address, the fourth will be the link quality with which the neighboring node heard the reporting node, and the fifth will be the link quality with which the reporting node heard the neighboring node reply. Thus data[0:3] would be the address of one node and data[5:8] would be the address of another node (assuming that the reporting node could communicate with two neighbors).

It is possible that one call to vmStat(12)() may result in multiple calls back to tellVmStat() from a given node if that node has many neighbors with which it can directly communicate. In dense networks, it may be necessary to include the “reply window” parameter in order to provide enough time for all nodes to respond.

This option for vmStat() was added in SNAP 2.6, and the reporting node must have version SNAP 2.6 (or later) firmware installed. However, neighboring nodes can have earlier firmware versions on them and still report correctly.

Note

Because of the callback() function, some of the vmStat() capabilities are redundant.

writePin

writePin(pin, isHigh)

Sets the current level of a digital output pin.

Parameters
  • pin (int) – Specifies which SNAPpy IO pin to configure.

  • isHigh (bool) – Sets the SNAPpy IO pin high when True; low when False.

Returns

None

Note

This SNAPpy IO pin must first be configured as a digital output pin using setPinDir().

See also

  • Refer to SNAP Modules for SNAPpy IO pin numbers

  • setPinSlew() - controls how quickly the pin will transition to a new value

xrange

xrange(args)

New in version SNAP 2.6.

Creates a sequence iterator.

Parameters

args – Given a single integer as an argument, returns an iterator that yields integers beginning with zero and stepping up to one less than the passed argument. Given two integers, it returns an iterator that yields integers beginning with the first argument and steps up to one less than the second argument. Given three integers, it returns an iterator that yields integers beginning with the first argument and steps toward (but stops just before reaching or passing) the second argument, stepping in increments of the third argument.

Returns

An iterable that can be stepped through using a for loop.

Examples

There are three ways the function can be called:

for i in xrange(3):
    print i, # Prints 012

for i in xrange(3, 6):
    print i, # Prints 345

for i in xrange(3, 9, 2):
    print i, # prints 357

Note

Remember that SNAPpy integers are 16-bit signed numbers. Unlike a while loop that continually increments a counter until the stop value is reached, xrange() will generate an iterable that yields no numbers if the start value is greater than the stop value, unless the step value is negative.