Sun™ Small Programmable Object Technology (Sun SPOT) Developers’ Guide This version of the Guide refers to V2.0 (updated 16-April-2007) Copyright 2005-2007 Sun Microsystems, Inc. All Rights Reserved.
Copyright © 2007 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved. Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is described in this document. In particular, and without limitation, these intellectual property rights may include one or more of the U.S. patents listed at http://www.sun.com/patents and one or more additional patents or pending patent applications in the U.S.
Contents Introduction .................................................................................................................................... 5 Building and deploying Sun SPOT applications .............................................................................. 6 Deploying and running a sample application ................................................................................................ 6 Deploying a pre-existing jar ..........................................................
Writing a device driver............................................................................................................................................ 40 http protocol support ................................................................................................................................... 41 Configuring the http protocol .................................................................................................................................. 41 Socket Proxy GUI mode .
Introduction The purpose of this guide is to aid developers of applications for Sun SPOTs. The guide is divided into two sections. Building and deploying Sun SPOT applications provides information about how to build, deploy and execute Sun SPOT applications.
Building and deploying Sun SPOT applications Deploying and running a sample application The normal process for creating and running an application (assuming you are working from the command line rather than an IDE) is: • • • • Create a directory to hold your application. Write your Java code. Use the supplied ant script to compile the Java and bind the resulting class files into a deployable unit. Use the ant script to deploy and run your application.
[delete] Deleting directory C:\MyApplication\build [delete] Deleting directory C:\MyApplication\suite [delete] Deleting directory C:\MyApplication\j2meclasses -post-clean: clean: -pre-compile: -do-compile: [mkdir] Created dir: C:\MyApplication\build [javac] Compiling 1 source file to C:\MyApplication\build -post-compile: compile: -pre-preverify: -make-preverify-directory: [mkdir] Created dir: C:\MyApplication\j2meclasses -unjar-utility-jars: -do-preverify: -post-preverify: preverify: -pre-jar-app: -find-man
-post-init: init: -override-warning-find-spots: -main-find-spots: [echo] Using Sun SPOT device on port COM45 -do-find-spots: slots: -run-spotclient-with-optional-remoteId: -run-spotclient-with-script-contents: -run-spotclient: [java] Waiting for target to synchronise... [java] (please reset SPOT if you don't get a prompt) [java] [waiting for reset] [java] Sun SPOT bootloader (1514-20060824) [java] SPOT serial number = 0014.4F01.0000.
or ant –Dport=COM2 info The difference between these two commands is that the “spotport” version will check that there is a Sun SPOT connected to the specified port, whereas the “port” version will attempt to connect to a Sun SPOT on the specified port regardless. You should normally use the “spotport” version. If you prefer, you may specify the port in the build.
[exec] [Adding property key: MIDlet-Vendor value: Sun Microsystems Inc] [exec] [Adding property key: MIDlet-1 value: Spottests,, squawk.application.Startup] [exec] [Adding property key: MIDlet-2 value: TestMIDlet label,, com.sun.spot.TestIMlet] [exec] [Adding property key: MicroEdition-Profile value: IMP-1.0] [exec] [Adding property key: MicroEdition-Configuration value: CLDC-1.1] [exec] [Including resource: res1.txt] [exec] Created suite and wrote it into image.
-do-init: -post-init: init: environment: [java] To configure the environment for Squawk, try the following command: [java] set JVMDLL=C:\jdk1.5.0_06\jre\bin\client\jvm.dll BUILD SUCCESSFUL Total time: 0 seconds C:\MyApplication> 6. Run the application. To run the application, use the “ant run” command. C:\MyApplication>ant run Buildfile: build.
[java] [java] [java] [java] -------------------------------------------------------------------Hits Class:95.74% Monitor:92.38% Exit:100.00% New:98.43% GCs: 2 full, 0 partial ** VM stopped: exit code = 0 ** [java] Exiting [delete] Deleting: C:\SunSPOT\dev\temp\spot-temp-674916937 -post-run: run: BUILD SUCCESSFUL Total time: 10 seconds C:\MyApplication> As you can see, this application just prints “Hello world!” However, it gives you a framework to use for your applications. N.B.
Excluding files from the compilation To exclude files or folders matching a specific pattern from the java compilation, set the ant property spot.javac.exclude.src, either on the command line with –D or in the build.properties file of the project. The value of the property should be specified using standard ant wildcarding. For example, to exclude all source files in all “unittests” folders, use: spot.javac.exclude.src=**/unittests/* Manifest and resources The file MANIFEST.
resources/META-INF/MANIFEST.MF within its root folder. The adderlib extension has such a file, whose content is FavouriteSnake: Viper This defines a property whose value will be available to all applications in a similar fashion to application-specific manifest properties. The addertest application demonstrates this by displaying the value of this property. The library suite is built to contain all the properties defined by the manifests of all its input jars.
Host Sun SPOT USB Sun SPOT (“base s tation”) (“Target”) 802.15.4 radio The Host can be any of the supported platforms (e.g. Windows PC, Mac). The Host application is a J2SE program. The Target application is a Squawk Java program. In the SPOT SDK and documentation the 64-bit addresses that identify SPOTs are expressed as sixteen hexadecimal digits subdivided into four groups that are separated by dots for readability. The Basestation may run in either dedicated or shared mode.
Base Station configuration It is possible to select a channel and pan id for the base station using command line properties in conjunction with ant host-run. The properties are: -Dremote.channel=nn -Dremote.pan.id=nn Alternatively, if you are operating in dedicated mode, the IRadioPolicyManager interface provides operations to adjust the output power of the radio, the PAN Id and the channel number. To access the policy manager from your host program do: Spot.getInstance().
To configure the SPOT so that this thread is started each time the SPOT starts issue this command via a USB connection: ant enableota The SPOT remembers this setting in its configuration area in flash memory. To configure the SPOT so that the OTA Command Server is not started each time the SPOT starts issue this command: ant disableota Although the OTA Command Server thread runs at maximum Thread priority, parts of the radio stack run at normal priority.
remote.pan.id either on the command line or in the .sunspot.properties file in your user root folder. Using short names for SPOTs As a shortcut, it is possible to use short names for SPOTs instead of the full 16-digit IEEE address. To do this create a file called “spot.names” in your user home directory. The file should contain entries of the form: = for example my-spot-1=0014.4F01.0000.
Even if you aren’t concerned about security, you need to be aware of this if you want to be able to use Sun SPOTs interchangeably amongst two or more SDK installations. See the section Sharing Sun SPOTs. Changing the owner of a Sun SPOT Once set, only the owner can change the public key remotely, although anyone who has physical access to the Sun SPOT can also change the public key.
ant deploy for each Sun SPOT. What is protected? Applications and customized libraries are always verified and unless the digital signature can be successfully verified using the trusted public key, the application will not be executed. Extra security is provided for over-the-air deployment. In this case, all updates to the configuration page are verified before the page is updated.
When the switch is specified a basestation will still be correctly identified if one is available, but if no basestation is available the port property will be set to dummyport. Your own host application You should base your host application on the template provided. Your host application can open connections in the usual way. The classes required to support this are in spotlib_host.jar, spotlib_common.jar and squawk_classes.jar (all in the lib sub-directory of the SDK install directory).
For situation 2 above you should configure the SPOT as a dedicated mesh router, using the command: ant selectmeshrouter When the SPOT is reset (by pressing the attention button or by an ant run command) it will begin acting as a dedicated router. A SPOT set in this configuration does not need the spot.mesh.enable property to be set. Trace route A SPOT can optionally run a trace route server. If a SPOT is running the trace route server it can participate in route tracing requests.
critical during the USB enumeration which occurs when plugging in a new device. During this phase the SPOT may only draw 20% (100mA) of its full power requirements. It is known that a SPOT with the demo sensor board requires more power than this during startup and therefore does not work on USB power alone. For the hardware configurations in the kit this is not an issue, but for custom configurations this constraint should be taken into account.
Developing and debugging Sun SPOT applications Overview of an application A Sun SPOT application is actually implemented as a MIDlet. This should not concern most developers greatly: the simplest thing is to copy a template, as described above, and start editing the copy. The most significant implications of this are covered in the section Manifest and resources. The Sun SPOT application runs on top of a number of other software components within the Sun SPOT.
The libraries only use system priorities in three cases: 1. To guarantee that application threads don't run during a system operation during which the system may be in an inconsistent state. 2. To guarantee short uninterruptible periods of operation for critical hardware interaction. 3. To ensure that the attention button is recognised. Threads are only assigned a permanent system priority to achieve 1. or 3.
Each physical device is controlled by a single instance of the respective class, accessed through the interfaces listed above. The single instance of the Sun SPOT class creates and manages access to the device driver singletons. The singletons are created only as required. For example, to get access to the on-board green LED, do: Iled theLed = Spot.getInstance().getGreenLed(); To turn the LED on and off: theLed.setOn(); theLed.
- there is a possibility that another isolate has written a new value for the property since the current isolate started your application has overwritten the user-defined property’s value in memory but not in flash (by executing System.setProperty). All user-defined properties can be accessed using: Spot.getInstance().
example above two sectors are allocated (and thus erased), starting with the first sector available to applications. Using the Record Management Store The Record Management Store (RMS) that is part of the Java IM Profile provides a simple recordbased mechanism for access to persistent data. Here is a very simple example of using the record store: RecordStore rms = RecordStore.openRecordStore("TEST", true); byte[] inputData = new byte[]{12,13,14,15,16}; int recordId = rms.addRecord(inputData, 0, inputData.
Configuring USART parameters The URL for USART access can uniquely be extended with additional parameters to configure the USART if required. For example: InputStream inputStream = Connector.openInputStream( "serial://usart?baudrate=57600&databits=7&parity=even&stopbits=1.5"); databits may be 5, 6, 7 or 8, parity can be none, even, odd, space or mark, and stop bits can be 1, 1.5 or 2. You need specified only those options you wish to change.
The radiogram protocol provides datagram-based communication between two devices. This protocol provides no guarantees about delivery or ordering. Datagrams sent over more than one hop could be silently lost, be delivered more than once, and be delivered out of sequence. Datagrams sent over a single hop will not be silently lost or delivered out of sequence, but they could be delivered more than once4. The protocols are implemented on top of the MAC layer of the 802.15.4 implementation.
Program 2 RadiostreamConnection conn = (RadiostreamConnection) Connector.open("radio://0014.4F01.0000.0007:100"); DataInputStream dis = conn.openDataInputStream(); DataOutputStream dos = conn.openDataOutputStream(); try { String question = dis.readUTF(); if (question.equals("Hello up there")) { dos.writeUTF("Hello down there"); } else { dos.writeUTF("What???"); dos.flush(); } } catch (NoRouteException e) { System.out.println ("No route to 0014.4F01.0000.0007"); } finally { dis.close(); dos.close(); conn.
where serverAddr is the 64bit IEEE Address of the radio of the server, and portNo is a port number in the range 0 to 255 that identifies this particular connection. Note that 0 is not a valid IEEE address in this implementation. The port number must match the port number used by the server. Data is sent between the client and server in datagrams, of type Datagram. To get an empty datagram you must ask the connection for one: Datagram dg = conn.newDatagram(conn.
There are some points to note about using datagrams: • Only datagrams obtained from the connection may be passed in send or receive calls on the connection. You cannot obtain a datagram from one connection and use it with another. • A connection opened with a specific address can only be used to send to that address. Attempts to send to other addresses will result in an exception. • It is permitted to open a server connection and a client connection on the same machine using the same port numbers.
There are some important points to note about using this operation: • • • • If setting a timeout it must be set before opening streams or creating datagrams. A TimeoutException is generated if the caller is blocked waiting for input for longer than the period specified. Setting a timeout of 0 causes the exception to be generated immediately if data is not available. Setting a timeout of -1 turns off timeouts, that is, wait forever. Broadcasting It is possible to broadcast datagrams.
The following table explains the current usage of ports in the reserved range.
DefaultChannelNumber DefaultPanId DefaultTransmitPower Turning the receiver off and on The radio receiver is initially turned off, but turns on automatically when either a radiogram connection capable of receiving is opened (that is, a non-broadcast radiogram connection) or when an input stream associated with a radio connection is opened. The receiver is turned off automatically when all such connections are closed.
RSSI (received signal strength indicator) measures the strength (power) of the signal for the packet. It ranges from +60 (strong) to -60 (weak). To convert it to decibels relative to 1 mW (= 0 dBm) subtract 45 from it, e.g. for an RSSI of -20 the RF input power is approximately -65 dBm. CORR measures the average correlation value of the first 4 bytes of the packet header.
• • • • • • • CPU – power on but CPU clock off (the CPU's power saving mode) Master system clocks – power on Low level firmware – power on RAM – power on but inactive Flash memory – power on but inactive CC2420 radio – power on AT91 peripherals – power on Because power is maintained to all the devices the Sun SPOT continues to react to external events such as the arrival of radio data. The Sun SPOT also resumes from shallow sleep without any latency.
If it is important that your application knows whether or not deep sleep happened, then you can alternatively execute this code: ISleepManager sleepManager = Spot.getInstance().getSleepManager(); SleepManager.ensureDeepSleep(5000); This code will either deep sleep for the specified time of 5,000 milliseconds, or throw an UnableToDeepSleepException to explain why deep sleep was not possible. In this case no sleeping will happen, deep or shallow.
2. Of all threads executing a Thread.sleep() it determines which will resume soonest. If the sleep interval is less than the minimum deep sleep time it shallow sleeps. 3. If the sleep interval is at least the minimum deep sleep time and deep sleeping is enabled, it sends a request to the SleepManager thread. 4. The SleepManager checks whether the Sun SPOT is connected to USB. If it is, a shallow sleep is performed. 5.
http protocol support The http protocol is implemented to allow remote SPOT applications to open http connections to any web service accessible from a correctly configured host computer. To open a connection do: HttpConnection connection = (HttpConnection)Connector.open("http://host:[port]/filepath"); Where host is the Internet host name in the domain notation, e.g. www.hut.fi or a numerical TCP/IP address. port is the port number, which can usually be omitted, in which case the default of 80 applies.
HTTP Proxy If the host computer running the Socket Proxy is behind a proxy server, the device can still access the Internet if the following property is specified in the MANIFEST.MF: com.sun.squawk.io.j2me.http.Protocol-HttpProxy: : where proxyaddress is the hostname or IP address of the HTTP proxy server and port is the proxy's TCP port. Socket Proxy GUI mode The SocketProxy program actually has two modes it can run in. The default as shown earlier, which presents a headless version.
Classpath configuration The classpath for an application that runs on a Sun SPOT needs to include the following jars in this order: SDK_INSTALL_DIRECTORY/lib/transducerlib_rt.jar SDK_INSTALL_DIRECTORY/lib/multihoplib_rt.jar SDK_INSTALL_DIRECTORY/lib/spotlib_device.jar SDK_INSTALL_DIRECTORY/lib/spotlib_common.jar SDK_INSTALL_DIRECTORY/lib/squawk_rt.jar The classpath for a host application that uses the base station needs to include the following jars in this order: SDK_INSTALL_DIRECTORY/lib/multihoplib_rt.
where xxxx is the id of the SPOT running the application being debugged and yyyy is the id of your base station. Note that xxxx can be a short name, as described in the Remote section, but yyyy cannot. If you regularly use the same basestation you can define the basestation.addr property in the .sunspot.properties file in your user root folder and then omit it from the command line. The SPOT will be restarted with the SDA running; your application will not start.
Using non-default channel or pan id It is not possible for an application being debugged to select dynamically a different channel or pan id. Instead the required channel or pan id must be selected using manifest properties (see section Using manifest properties to adjust the radio). Then the required channel or pan id can be specified like this: ant debug -DremoteId=spot1 -Dremote.channel=11 –Dremote.pan.
Expand each of the first four of these, then select and edit the “Source attachment”. Point this to the relevant source jar as follows: transducerlib_rt.jar multihoplib_rt.jar spotlib_common.jar spotlib_host.jar SDK_INSTALL_DIRECTORY/src/transducerlib_source.jar SDK_INSTALL_DIRECTORY/src/multihoplib_source.jar SDK_INSTALL_DIRECTORY/src/spotlib_source.jar SDK_INSTALL_DIRECTORY/src/spotlib_source.jar You may need to create a new Eclipse classpath variable to do this.
Start by copying LibraryExtensionSampleCode to a working area. This contains two sub-directories: adderlib and addertest. adderlib contains the library. You should find a sub-directory containing the library Java source: you can add to or edit this as you see fit. 1. Build any new .jar files containing additions to the library With adderlib as your current directory, execute the command ant jar-app to create a jar file containing the library extension.
Note that by default, the library is built without line number information to save space in flash memory. For debugging purposes, you may find it useful to build it with line number information, which will put line number information in stack traces. To do this, do ant library –DKEEPSYMBOLS=true 4. Deploy the new library suite to your Sun SPOTs Use the command ant flashlibrary to flash the new library onto your Sun SPOTs. This command always flashes the library whose name is defined in .sunspot.
The source code for the libraries is supplied in three parts: spotlib_source.jar contains the code that supports the SPOT main board; multihop_source.jar contains the radio communications stack; and transducerlib_source.jar contains the code that supports the Demo Sensor Board. This example shows the process for rebuilding the library with a modified version of the source in spotlib_source.jar. The process for modifying any or all of the other source .jars is similar.
Wire objects together At system startup, a development tool should create and wire together various objects. This code shows the general style: String keyStorePath = "/foo/bar"; // path to user’s key store SpotManager spotManager = new SpotManager(keyStorePath); MyUIClass ui = new MyUIClass(); SerialPortTarget spt = new SerialPortTarget(); spt.initialise("COM3", ui); //port to which Spot is attached spotManager.
Reference Persistent system properties Property name spot.hardware.rev spot.powercontroller.firmware.version spot.sdk.version spot.external.0.part.id spot.external.0.hardware.rev spot.external.0.firmware.version spot.external.1.part.id spot.external.1.hardware.rev spot.external.1.firmware.version Meaning The first three of these properties define the hardware, power controller firmware and SDK software versions installed on the SPOT. The items starting spot.external.
Memory usage The Sun SPOT flash memory runs from 0x10000000 to 0x10400000 (4M bytes), and is organized as 8 x 8Kb followed by 62 x 64Kb followed by 8 x 8Kb sectors.
debugger_classes.jar desktop_signing.jar j2se_classes.jar junit.jar multihoplib_rt.jar networktools.jar romizer_classes.jar RXTXcomm.jar rxtxSerial.dll sdp_classes.jar sdproxylauncher.jar singlehoplib_rt.jar socket_proxy.jar spotclient.jar spotlib_common.jar spotlib_device.jar spotlib_host.jar squawk.jar squawk.suite squawk.sym squawk_classes.jar squawk_rt.jar transducerlib_rt.jar translator.suite translator_classes.jar Contents of the bin directory: preverify.exe spotfinder.exe squawk.
Contents of the src directory: multihoplib_source.jar sdproxylauncher_source.jar singlehoplib_source.jar spotclient_source.jar spotlib_host_source.jar spotlib_source.jar spotselector_source.jar transducerlib_source.jar Contents of the doc directory: spot-developers-guide.pdf README.txt javadoc Source code for the radio communications stack. Source code for the debugger proxy program. Source code for the old single-hop-only radio communications stack. Source code for the SpotClient program.